4月30天leetcode训练-Day30最后一天!!!

Day30-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.

从一个二叉树中找到给定字符串的合法路径,所谓合法路径是从根节点到叶子节点。

解法:

例子就不贴了,说实话这个30天挑战的最后一题挺失望的,原以为大结局应该是道巨难的题,都已经准备看一眼找答案了,结果发现是这么个题,就是用DFS递归方法一步步写就能出来了。设置递归函数,传入当前在树的节点和当前数组中的位置,判断这个节点的值和数组的值是否相等,然后到最后一个数字时除了判断对应值是否相等,还要判断是否是叶子节点。再有一点是有可能有多条路径满足要求,所以用or来连接左右子树的情况。

现在这个代码是我直接把上面的想法写出来的版本,所以感觉思维还是有点乱,用了很多条件语句,其实应该还可以更简洁一些的。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isValidSequence(self, root: TreeNode, arr: List[int]) -> bool:
        start = 0
        def helper(root,start,arr):
            if start == len(arr) - 1:
                if root:
                    if root.val == arr[start]:
                        if root.left is None and root.right is None:
                            return True
                        else:
                            return False
                    else:
                        return False
                else:
                    return False
            else:
                if root is None:
                    return False
                else:
                    if root.val == arr[start]:
                        return helper(root.left,start + 1,arr) or helper(root.right,start + 1,arr)
                    else:
                        return False
        return helper(root,start,arr)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值