I am trying to find out how to get the path from root to a given node on a binary tree.
It is not binary search tree.
Each non-leaf node has only two point
public List> getPath(T data){
Stack> stack = new Stack>();
Boolean found = getPath(root, stack, data);
List> path = new ArrayList>();
if(!found){
return path;
}
return Arrays.asList(stack.toArray((Node[])new Node[stack.size()]));
}
public Boolean getPath(Node node, Stack> stack, T data){
if(node == null){
return false;
}
stack.push(node);
if(node.data.equals(data)){
return true;
}
Boolean found = getPath(node.left, stack, data) ||
getPath(node.right, stack, data);
if(!found ){
stack.pop();
}
return found;
}