How to Implement DFS & BFS Traversal in Java

Depth-first search (DFS) and best-first search (BFS) are two traversals you can run on Java tree structures. They start at a specified node and branch out until they find the search object. The only difference is the directionality: DFS searches down from the node, BFS searches horizontally to neighboring nodes. Implementing DFS and BFS traversals is relatively simple, because, though the code is long, there are only a couple places where it needs to be customized for your data.

Instructions

    • 1

      Open your Java code.

    • 2

      Copy and paste the following where you want the traversal to run:
      public void TRAV()
      {
      Stack s=new Stack();
      s.push(this.rootNode);
      rootNode.PROP;
      printNode(rootNode);
      while(!s.isEmpty())
      {
      Node n=(Node)s.peek();
      Node child=getUnvisitedChildNode(n);
      if(child!=null)
      {
      child.visited=true;
      printNode(child);
      s.push(child);
      }
      else
      {
      s.pop();
      }
      }
      clearNodes();
      }

    • 3

      Replace “TRAV” with either “dfs” or “bfs.”

    • 4

      Replace “PROP” with your search property. This can be any Java condition, using regular Java code.

    • 5

      Run the code. It will perform the DFS/BFS traversal and display the results in a new window when it finishes.

Related Searches:

References

Comments

Related Ads

Featured