面试150 路径总和

思路

在进行先序遍历时,首先判断递归终止的条件:若当前节点为空,则返回 False;若当前节点为叶子节点,且其值等于目标和,则返回 True。递归的核心逻辑是:分别对左右子树进行递归遍历,并在过程中更新目标和。

python 复制代码
class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        #只有有一条就够了,传入节点和相应的和
        def inorder(node,sum):
            if node==None:
                return False
            if node.left==None and node.right==None and node.val==sum:
                return True
            sum-=node.val
            Left=inorder(node.left,sum)
            Right=inorder(node.right,sum)
            return Left or Right
        
        if not root:
            return False
        return inorder(root,targetSum)
相关推荐
稳兽龙13 小时前
codeforces(1045)(div2)D. Sliding Tree
c++·算法··路径树
闪电麦坤951 天前
数据结构:红黑树(Red-Black Tree)
数据结构··红黑树
工藤新一¹1 天前
C/C++ 数据结构 —— 树(2)
c语言·数据结构·c++·二叉树··c/c++
闪电麦坤958 天前
数据结构:从前序遍历序列重建一棵二叉搜索树 (Generating from Preorder)
数据结构··二叉搜索树
闪电麦坤958 天前
数据结构:二叉树的遍历 (Binary Tree Traversals)
数据结构·二叉树·
pusue_the_sun8 天前
数据结构:二叉树oj练习
c语言·数据结构·算法·二叉树
崎岖Qiu10 天前
leetcode100.相同的树(递归练习题)
算法·leetcode·二叉树·力扣·递归
闪电麦坤9511 天前
数据结构:在二叉搜索树中插入元素(Insert in a BST)
数据结构·二叉树··二叉搜索树
闪电麦坤9511 天前
数据结构:用链式队列实现层序遍历 (Level-order Traversal)
数据结构··遍历
闪电麦坤9511 天前
数据结构:迭代方法(Iteration)实现树的遍历
数据结构·二叉树·