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)
本文探讨了如何在二叉树中验证一个给定的字符串是否为从根节点到叶子节点的有效路径。通过深度优先搜索(DFS)递归方法,我们检查路径上的每个节点值是否与数组中的值相匹配,并确认最后一节点是否为叶子节点。
143

被折叠的 条评论
为什么被折叠?



