0% completed
Problem Statement
Given a binary tree and a number sequence, find if the sequence is present as a root-to-leaf path in the given tree.
Constraints:
1 <= arr.length <= 5000
0 <= arr[i] <= 9
- Each node's value is between
[0 - 9]
.
Solution
This problem follows the Binary Tree Path Sum pattern. We can follow the same DFS approach and additionally, track the element of the given sequence that we should match with the current node. Also, we can return false
as soon as we find a mismatch between the sequence and the node value.
Here is the visual representation of the algorithm:
Code
Here is the code for this algorithm:
Time Complexity
The time complexity of the above algorithm is O(N), where āNā is the total number of nodes in the tree. This is due to the fact that we traverse each node once.
Space Complexity
The space complexity of the above algorithm will be O(N) in the worst case. This space will be used to store the recursion stack. The worst case will happen when the given tree is a linked list (i.e., every node has only one child).
.....
.....
.....
Table of Contents
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible