1618. Branch Pattern Count
A botanist records spore codes (digits 0 to 9) at the joints of a branching plant, stored as the binary tree root, and keeps a reference code sequence as the singly linked list head. Count the downward paths that spell the reference sequence exactly. A path starts at any node and every step moves from a node to one of its left or right children, and the values met along the way must equal the values of head, in order. Paths with different starting nodes are counted separately even when they overlap. The tree has up to 100000 nodes and may be one long chain, so the traversal must be iterative, and the list has up to 10000 nodes. Build the failure table of the list once and carry the matched length down the tree: O(n + m) time and space.
Example 1
- Input:
- root = [1,2,2,1,2,null,1], head = [1,2]
- Output:
- 2
- Explanation:
The pattern 1, 2 is read along the two paths from the root to its left child and to its right child.
Example 2
- Input:
- root = [5,5,5], head = [5]
- Output:
- 3
- Explanation:
A one-node pattern matches every node holding 5.
Constraints
1 ≤ tree nodes ≤ 105
1 ≤ list length ≤ 104
0 ≤ val ≤ 9
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n + m)
- Space
- O(n + m)