Given a binary tree with distinct nodes(no two nodes have the same data values). The problem is to get the path from root to a given node x.
Examples:
Input : 1
/ \
2 3
/ \ / \
4 5 6 7
x = 5
Output : 1->2->5
Solution
Approach 1: Recursive
public boolean getRootToNodePath(TreeNode root, TreeNode node,
List<TreeNode> path){
if(root == null){
return false;
}
// visit - add to path
path.add(root);
if(root.val == node.val){
path.add(root);
return true;
}
// search in left and right subtree
if(getRootToNodePath(root.left, node, path) ||
getRootToNodePath(root.right, node, path)){
return true;
}
// visit - remove from path
path.remove(path.size()-1);
return false;
}
Approach 2: Iterative