Leetcode513. 找树左下角的值 Find Bottom Left Tree Value - python 递归、迭代法

class Solution:
    def findBottomLeftValue(self, root: TreeNode) -> int:
        queue = deque()
        if root: 
            queue.append(root)
        result = 0
        while queue: 
            q_len = len(queue)
            for i in range(q_len): 
                if i == 0: 
                    result = queue[i].val 
                cur = queue.popleft()
                if cur.left: 
                    queue.append(cur.left)
                if cur.right: 
                    queue.append(cur.right)
        return result

层序遍历,迭代法:

层序遍历,for循环遍历queue队列中树最后一层叶子节点,就会得到最后一层。

if i==0 可以得到最后一层的第一个元素,which is 最左边的元素。有三种情况:

1.最后一层是满二叉树,全是叶子节点,则取最左边的

2.最后一层只有一个光杆司令 左 叶子节点,则取的是这个左光杆司令

3.最后一层只有一个光杆司令 右 叶子节点,则取得是右光杆司令,不过题目的cases应该没有这种情况所以排除。

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

        def traversal(root, depth):
            nonlocal max_depth, result
            if not root.left and not root.right:
                if depth > max_depth:
                    max_depth = depth
                    result = root.val
            if root.left:
                depth += 1
                traversal(root.left, depth)
                depth -= 1
            if root.right:
                depth += 1
                traversal(root.right, depth)
                depth -= 1
        traversal(root, 0)
        return result 

递归法:

递归三部曲:

1.递归参数、返回值

2.递归停止条件,当遍历到叶子节点时,停止。但需要做一些判断处理:

若当前为最大深度,则更新最大深度;

记录当前叶子节点值,因为这是最深最左的叶子节点(最左是怎么来的?不管是前中后序遍历,总是先遍历左孩子、然后右孩子。所以第一个遍历的孩子就是最左的孩子)

3.单层递归逻辑:

依次遍历当前节点的左孩子和右孩子

需要注意的是:

1.需要两个全局变量:max_depth 和 result

2.注意回溯思想,给每一次递归都分配了一个女秘书depth变量,记录当前深度。

当在本层调用下层递归时,需要先将本层depth+1,再传给下层;

当下层递归结束返回本层时,为保持depth变量值不变,需将depth-1

或者 直接传入traversal(root.left, depth + 1)

depth + 1 跟 求二叉树路径的 path + ' ->' 类似 是一种隐藏回溯

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值