The problem is simple. Given a node, we should be able to show the path from the root to that node in a BINARY TREE (NOT A BINARY SEARCH TREE). This solution would help us how to traverse through a binary tree. Here I am going to do an inorder traversal. More on traversals on a binary tree can be found
here.
Consider the following binary tree, we can see the path to be found and the node supplied to find it. We will be provided with a tree, its root and the node to be found.
76 is the item that we need to find. Although the example looks like a BINARY SEARCH TREE, we are not going to use the binary search tree way to find 76. So, we would have no other way than doing either of inorder, post-order or pre-order traversals.
To attack this problem,we maintain a stack. The stack will always maintain the path. Whenever we encounter the node to be found, we will stop our process and the path in the current stack will give the path to be found. The solution for this problem shown would be : 43,887,46,78,76
Now, for the Java code part,
package dsa.tree;
import java.util.Stack;
public class TracePath {
private Node n1;
private Stack<Node> mainStack = null;
public static void main(String args[]){
TracePath nodeFinder = new TracePath();
nodeFinder.find();
}
public void find(){
Tree t = getSampleTree();
trace(t,n1);
for(Node iNode:mainStack){
System.out.println(iNode.data);
}
}
private Tree getSampleTree() {
Tree bsTree = new BinarySearchTree();
int randomData[] = {43,887,11,3,8,33,6,0,46,32,78,76,334,45};
for(int i=0;i<randomData.length;i++){
bsTree.add(randomData[i]);
}
n1 = bsTree.search(76);
return bsTree;
}
public Stack<Node> trace(Tree t, Node node){
mainStack = new Stack<Node>();
trace(t.getRoot(),node);
return mainStack;
}
private boolean trace(Node parent, Node node){
mainStack.push(parent);
if(node.equals(parent)){
return true;
}
if(parent.left != null){
if (trace(parent.left, node))
return true;
}
if(parent.right!=null){
if (trace(parent.right, node))
return true;
}
mainStack.pop();
return false;
}
}