1599. Chain Along a Branch
A binary tree of departments is given by root, and a linked list of codes by head. A node of the tree is a valid start if the list's values can be read one by one going downward from it: the first list value equals the start node's value, the second equals the value of one of its children, the third the value of one of that child's children, and so on, using exactly as many nodes as the list has and always stepping to a left or right child.
The root has depth 0, its children depth 1, and so on. Return the smallest depth among all valid start nodes, or -1 if no node qualifies. A recursive match from every node examined level by level is enough: O(N * L) time at most with O(L + width) extra space.
Example 1
- Input:
- root = [2,1,3,1,2,null,2,null,null,3,null,null,1]head = [1,2,3]
- Output:
- 1
- Explanation:
Starting at the left child (depth 1, value 1), the path 1 -> 2 -> 3 matches the list.
Example 2
- Input:
- root = [4,4,5], head = [4,5]
- Output:
- 0
- Explanation:
The root 4 has a right child 5, so the root itself is a valid start at depth 0.
Constraints
1 ≤ tree nodes ≤ 2500; 1 ≤ list length ≤ 100; 1 ≤ val ≤ 100 for every tree and list node.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(N * L)
- Space
- O(N)