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

本文探讨了如何检查一个字符串是否为给定二叉树中从根到叶子的有效路径序列。通过深度优先搜索(DFS)算法,我们可以在二叉树中找到与输入数组匹配的路径,并判断其是否终止于叶子节点。文章提供了详细的解决方案和示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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:
img

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:
img

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:
img

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

Depth-first search (DFS) with the parameters: current node in the binary tree and current position in the array of integers.深度优先遍历

When reaching at final position check if it is a leaf node.

class Solution {
public:
    bool isValidSequence(TreeNode* root, vector<int>& arr) {
        return helper(root,arr,0);
    }
    bool helper(TreeNode * node,vector<int>& arr, int pos)
    {
        if(node==NULL)
            return false;
        if(node->val!=arr[pos])
           return false;

        if(pos==arr.size()-1)//数组完了,判断当前节点是不是叶节点
            return (node->left==NULL && node->right==NULL);

        return(helper(node->left,arr,pos+1)||helper(node->right,arr,pos+1));
    }
};

参考链接

leetCode

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值