Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. One starts at the root(selecting some arbitrary node as the root in the case of a graph) and explores as far as possible along each branch before backtracking.
DFS requires the use of a data structure called Stack, which is a Last In First Out (LIFO) structure.
Depth-First Traversal Sequence: 1 - 2 - 4 - 5 - 3 - 6
package interviewquestions;
import java.util.Stack;
class Node<T>
{
private T data;
private Node<T> left;
private Node<T> right;
Node( T pData, Node<T> pLeft, Node<T> pRight )
{
data = pData;
left = pLeft;
right = pRight;
}
public void setLeftChild( Node<T> pLeft ) { left = pLeft; }
public void setRightChild( Node<T> pRight ) { right = pRight; }
public Node<T> getLeftChild() { return left; }
public Node<T> getRightChild() { return right; }
public T getData() { return data; }
}
class BinaryTree<T>
{
Node<T> root;
public BinaryTree(){ root = null; }
public void setRootNode( Node<T> pRoot ) { root = pRoot; }
public void depthFirst()
{
depthFirst( root );
}
private void depthFirst( Node<T> pNode )
{
if( pNode == null )
return;
Stack<Node<T>> stack = new Stack<Node<T>>();
stack.add(pNode);
while (!stack.isEmpty()) {
Node<T> node = stack.pop();
if (node.getRightChild() != null)
stack.add(node.getRightChild());
if (node.getLeftChild() != null)
stack.add(node.getLeftChild());
System.out.print(node.getData());
}
}
}
public class DepthFirstTraversal {
public static void main(String[] args) {
Node<Integer> node1 = new Node<Integer>( 1, null, null );
Node<Integer> node2 = new Node<Integer>( 2, null, null );
Node<Integer> node3 = new Node<Integer>( 3, null, null );
Node<Integer> node4 = new Node<Integer>( 4, null, null );
Node<Integer> node5 = new Node<Integer>( 5, null, null );
Node<Integer> node6 = new Node<Integer>( 6, null, null );
node1.setLeftChild(node2);
node1.setRightChild(node3);
node2.setLeftChild(node4);
node2.setRightChild(node5);
node3.setRightChild(node6);
BinaryTree<Integer> binaryTree = new BinaryTree<Integer>();
binaryTree.setRootNode(node1);
binaryTree.depthFirst();
}
}
Create a DepthFirstTraversal.java file in your workspace.
When the main method inside the DepthFirstTraversal class executed it is going to print :
1
2
4
5
3
6

No comments:
Post a Comment