Binary Trees Depth first: return a value up
363. Path from the Root to a Node
You are given root, the root node of a binary tree, and an integer target. The values in the tree are
distinct, and one node holds target. Return the values on the path from the root down to that node, in
order. The path starts with the root's value and ends with target.
The tree is not a binary search tree. Its values can be in any order.
The examples write a tree level by level, from left to right, with null where a child is missing. So
root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The
missing children after the last node are left out.
Example 1
Input: root = [4, 9, -3, 1, 6, null, 8, null, null, 2, 7]
target = 7
[4,9,6,7]Explanation: 7 is the right child of 6, 6 is the right child of 9, and 9 is the left child of the root 4. The other nodes are not on the way down to 7.
Example 2
Input: root = [0, -5, 5], target = 0
[0]Explanation: target is the root, so the path is the root alone.
Example 3
Input: root = [-1000000000, null, 1000000000, 7]
target = 7
[-1000000000,1000000000,7]Explanation: The root has only a right child, 1000000000, and 7 is that child's left child.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ number of nodes ≤ 105-109 ≤ Node.val ≤ 109- The tree has at most 1000 levels.
- All the values in the tree are distinct.
targetis the value of a node in the tree.
Clarifying questions
What you would ask an interviewer before writing any code.