Problem
Section titled “Problem”Given a Binary Tree A containing N nodes.
You need to find the path from Root to a given node B.
NOTE:
- No two nodes in the tree have same data values.
- You can assume that
Bis present in the treeAand a path always exists.
The first argument is a pointer to the root of the binary tree A; the second is an integer B denoting the node number. Return a one-dimensional array denoting the path from the root to the node B, in order.
Example 1:
Input: A = 1 / \ 2 3 / \ / \ 4 5 6 7 B = 5Output: [1, 2, 5]Explanation: We need to find the path from root node to node with data value 5.So the path is 1 -> 2 -> 5 so we will return [1, 2, 5].Example 2:
Input: A = 1 / \ 2 3 / \ \ 4 5 6 B = 1Output: [1]Explanation: We need to find the path from root node to node with data value 1.As node with data value 1 is the root so there is only one node in the path. So we will return [1].Constraints:
- data value of each node
Solution approach
Section titled “Solution approach”Intuition
Section titled “Intuition”During a depth-first search, the nodes on the recursion stack are exactly the path from the root to the node currently being visited. So if we keep that stack as an explicit array path — push a node when we enter it, pop it when we leave it — then at the moment we reach the node with value B, path is the answer, already in root-to-node order.
When a subtree does not contain B, the search returns false and the node is popped again, so dead ends leave no trace. As soon as B is found, every caller returns true immediately without popping, which freezes path.
Algorithm
Section titled “Algorithm”findPath(node, B, path)returns whetherBlies in the subtree ofnode:- If
nodeis null, returnfalse. - Push
node->valontopath. - If
node->val == B, orfindPathsucceeds in the left subtree, or in the right subtree, returntrue(leavenodeon the path). - Otherwise pop
node->valand returnfalse.
- If
solve(A, B)callsfindPath(A, B, path)on an emptypathand returns it.
Walkthrough
Section titled “Walkthrough”Example 1: the search enters 1, 2, 4 (dead end, popped), then 5 = B. Green nodes are the returned path, red the dead end that was backtracked; 3 and its subtree are never visited:
Complexity
Section titled “Complexity”- Time: — each node is entered at most once, and the search stops as soon as
Bis found. - Space: — the recursion stack and
pathboth hold at mosthnodes, wherehis the height ( for a skewed tree).
Edge cases
Section titled “Edge cases”Bis the root (Example 2): the first call matches and returns[A->val].Bis a deep leaf in a skewed tree:pathgrows toNentries; it is still exactly the root-to-node path.
Think before you peek
Work out an approach on your own first — the explanation will still be here when you want it.
bool findPath(TreeNode* node, int B, vector<int>& path) { if (!node) return false; path.push_back(node->val); if (node->val == B || findPath(node->left, B, path) || findPath(node->right, B, path)) return true; path.pop_back(); return false;}
vector<int> Solution::solve(TreeNode* A, int B) { vector<int> path; findPath(A, B, path); return path;}public class Solution { public ArrayList<Integer> solve(TreeNode A, int B) { // Iterative DFS (a skewed tree can be 10^5 deep): `path` is the stack of // nodes from the root to the current node, `last` the subtree just finished. ArrayList<TreeNode> path = new ArrayList<>(); TreeNode node = A, last = null; while (node != null || !path.isEmpty()) { if (node != null) { path.add(node); if (node.val == B) break; node = node.left; } else { TreeNode top = path.get(path.size() - 1); if (top.right != null && top.right != last) { node = top.right; } else { last = path.remove(path.size() - 1); // dead end: backtrack } } } ArrayList<Integer> result = new ArrayList<>(path.size()); for (TreeNode t : path) result.add(t.val); return result; }}class Solution: # @param A : root node of tree # @param B : integer # @return a list of integers def solve(self, A, B): # Iterative DFS (a skewed tree can be 10^5 deep): `path` is the stack of # nodes from the root to the current node, `last` the subtree just finished. path = [] node, last = A, None while node or path: if node: path.append(node) if node.val == B: break node = node.left else: top = path[-1] if top.right and top.right is not last: node = top.right else: last = path.pop() # dead end: backtrack return [t.val for t in path]Give it a try first
Attempt the problem on InterviewBit — the code will still be here.
