check-string-valid-sequence-from-root-to-leaves-path-in-bst

Problem

Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Treearrow-up-right

Problem Description

Given a binary tree where each path going from the root to any leaf form a valid sequence, check if a given string is a valid sequence in such binary tree. 

We get the given string from the concatenation of an array of integers arr and the concatenation of all values of the nodes along a path results in a sequence in the given binary tree.


Example 1:
example 1

Example 2:

example 2
example 3

Constraints:

  • 1 <= arr.length <= 5000

  • 0 <= arr[i] <= 9

  • Each node's value is between [0 - 9].

Solution

DFS, check root to leaf every path, compare with arr, if found return true. otherwise return false.

for example:

Valid String Sequence from Root to Leaves DFS

Complexity Analysis

Time Complexity: O(N)

  • N - Number of nodes

Code

DFS Java code

BFS Java Code

Using BFS, sweep each level and compare with arr[idx], if idx at last index of arr and current node is leaf, then found valid sequence. otherwise continue.

For example:

Valid String Sequence from Root to Leaves BFS

Last updated