Path With Given Sequence (medium)

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.

Created with Fabric.js 1.6.0-rc.1 Example 1: Sequence: [1, 9, 9]Output: true Explaination: The tree has a path 1 -> 9 -> 9. 1 7 9 2 9
Created with Fabric.js 1.6.0-rc.1 Example 2: 1 0 1 1 6 5 Sequence: [1, 0, 7]Output: false Explaination: The tree does not have a path 1 -> 0 -> 7. Sequence: [1, 1, 6]Output: true Explaination: The tree has a path 1 -> 1 -> 6.

Try it yourself #

Try solving this question here:

Output

0.498s

Tree has path sequence: False Tree has path sequence: False

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:

Output

0.975s

Tree has path sequence: False Tree has path sequence: True

Time complexity #

The time complexity of the above algorithm is O(N)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)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).

Mark as Completed
←    Back
Sum of Path Numbers (medium)
Next    →
Count Paths for a Sum (medium)