二叉树左下角值/路径总和

513.找树左下角的值

在这里插入图片描述
那么如果找最左边的呢?可以使用前序遍历,这样才先优先左边搜索,然后记录深度最大的叶子节点,此时就是树的最后一行最左边的值。

# 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 findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        que = deque([root])
        res = 0
        while que:
            size = len(que)
            for i in range (size):
                # 每一层都记录第一个结点的值
                if i == 0:
                    res = que[i].val
                cur = que.popleft()
                if cur.left:
                    que.append(cur.left)
                if cur.right:
                    que.append(cur.right)
        return res

                

class Solution:
    def findBottomLeftValue(self, root: TreeNode) -> int:
        max_depth = -float("INF")
        leftmost_val = 0

        def __traverse(root, cur_depth): 
            nonlocal max_depth, leftmost_val
            if not root.left and not root.right: 
                if cur_depth > max_depth: 
                    max_depth = cur_depth
                    leftmost_val = root.val  
            if root.left: 
                cur_depth += 1
                __traverse(root.left, cur_depth)
                cur_depth -= 1
            if root.right: 
                cur_depth += 1
                __traverse(root.right, cur_depth)
                cur_depth -= 1

        __traverse(root, 0)
        return leftmost_val

112. 路径总和

在这里插入图片描述

再来看返回值,递归函数什么时候需要返回值?什么时候不需要返回值?这里总结如下三点:

如果需要搜索整棵二叉树且不用处理递归返回值,递归函数就不要返回值。(这种情况就是本文下半部分介绍的113.路径总和ii)
如果需要搜索整棵二叉树且需要处理递归返回值,递归函数就需要返回值。 (这种情况我们在236. 二叉树的最近公共祖先 (opens new
window)中介绍) 如果要搜索其中一条符合条件的路径,那么递归一定需要返回值,因为遇到符合条件的路径了就要及时返回。(本题的情况)

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def hasPathSum(self, root, targetSum):
        """
        :type root: TreeNode
        :type targetSum: int
        :rtype: bool
        """
        def traversal(root, count):
            # 如果count为0 且为叶子节点 说明到尽头 找到了路径返回真
            # 中 处理单层逻辑
            if not root.left and not root.right and count == 0:
                return True 
            # 叶子节点 说明到尽头 假
            if not root.left and not root.right:
                return False
            
            # 左 
            if root.left:
                count -= root.left.val
                if traversal(root.left, count):return True #递归 处理左节点
                count += root.left.val #回溯
    
            # 右
            if root.right:
                count -= root.right.val
                if traversal(root.right, count):return True
                count += root.right.val#回溯
            
            return False

        if root == None:
            return False
        return traversal(root, targetSum - root.val)

113. 路径总和ii

在这里插入图片描述113.路径总和ii要遍历整个树,找到所有路径,所以递归函数不要返回值!

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def pathSum(self, root, targetSum):
        """
        :type root: TreeNode
        :type targetSum: int
        :rtype: List[List[int]]
        """

        def traversal(root, count):
            # 如果count为0 且为叶子节点 说明到尽头 找到了路径 添加
            # 中 处理单层逻辑
            if not root.left and not root.right and count == 0:
                result.append(path[:])# 注意这里不能写成result.append(path)
                return
            
            # 叶子节点 说明到尽头 直接返回
            if not root.left and not root.right:
                return 
            
            # 左 
            if root.left:
                path.append(root.left.val)
                count -= root.left.val
                traversal(root.left, count)
                count += root.left.val #回溯
                path.pop()#回溯

    
            # 右
            if root.right:
                path.append(root.right.val)
                count -= root.right.val
                traversal(root.right, count)
                count += root.right.val#回溯
                path.pop()#回溯
            
           

        result = []
        path = []
        if not root:
            return []
        path.append(root.val)
        traversal(root, targetSum -root.val)
        return result


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值