Problem Description
Given a binary tree where each root-to-leaf path represents a potential sequence, determine if a given sequence (represented as an array of integers) exists as a valid path in the tree. The sequence is valid only if it matches exactly the values from the root to a leaf node.
Key Insights
- Use a depth-first search (DFS) approach to traverse the tree while tracking the current index in the sequence.
- At each node, verify that the node’s value matches the sequence element at the current index.
- When the end of the sequence is reached, confirm that the current node is a leaf.
- Return false if the tree path deviates from the sequence at any point.
Space and Time Complexity
Time Complexity: O(N), where N is the number of nodes in the tree, since in the worst-case we might traverse all nodes. Space Complexity: O(H), where H is the height of the tree due to the recursion stack.
Solution
We use a recursive DFS to verify the sequence. The algorithm starts at the root and at each recursive call:
- Check if the current node is null or if its value does not match the sequence element at the current index; if so, return false.
- If the current index is the last element in the sequence, check if the current node is a leaf (i.e., no children). If it is, return true.
- Otherwise, recursively call the DFS for the left and right subtrees, advancing the index by one. The recursion stops when a valid path is found or when all possibilities are exhausted.