Path With Given Sequence (medium)
We'll cover the following
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.
Try it yourself #
Try solving this question here:
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.
Code #
Here is what our algorithm will look like:
Time complexity #
The time complexity of the above algorithm is , 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 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).