Leetcode - Add One Row to Tree
Leetcode - Maximum Depth of N-ary Tree

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

violet posted @ May 01, 2020 05:57:26 AM in 算法 with tags tree DFS Golang Algorithm , 227 阅读

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

 

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isValidSequence(root *TreeNode, arr []int) bool {
    return find(root, arr, 0)
}

func find(root *TreeNode, arr []int, index int) bool {
    if root == nil {
        return len(arr) == index
    }
    
    if root.Val == arr[index] && root.Left == nil && root.Right == nil && index == len(arr) - 1{
        return true
    }
    return (index < len(arr)-1) && (root.Val == arr[index]) && (find(root.Left, arr, index+1) || find(root.Right, arr, index+1))
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter