Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree

April 30, 2020

Introduction

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:

Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,0,1]
Output: true
Explanation: 
The path 0 -> 1 -> 0 -> 1 is a valid sequence (green color in the figure). 
Other valid sequences are: 
0 -> 1 -> 1 -> 0 
0 -> 0 -> 0

Example 2:

Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,0,1]
Output: false 
Explanation: The path 0 -> 0 -> 1 does not exist, therefore it is not even a sequence.

Example 3:

Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,1]
Output: false
Explanation: The path 0 -> 1 -> 1 is a sequence, but it is not a valid sequence.

Constraints:

    1 <= arr.length <= 5000
    0 <= arr[i] <= 9
    Each node's value is between [0 - 9].

Solution

Let’s do the simple recursion solution.

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isValidSequence(root *TreeNode, arr []int) bool {
    if root == nil {
        return len(arr) == 0
    }
    if len(arr) == 0 {
        return false
    }
    if root.Val != arr[0] {
        return false
    }
    leaf, left, right := true, false, false
    if root.Left != nil {
        left = isValidSequence(root.Left, arr[1:])
        leaf = false
    }
    if root.Right != nil {
        right = isValidSequence(root.Right, arr[1:])
        leaf = false
    }
    if leaf && len(arr) == 1 {
        return true
    }
    return left || right
}

comments powered by Disqus

Do you want to know me more private?→Click!