力扣每日一题:513.找树左下角的值 Python DFS 、BFS双解!

513.找树左下角的值

https://leetcode-cn.com/problems/find-bottom-left-tree-value/

难度:中等

题目:

给定一个二叉树,在树的最后一行找到最左边的值。

示例:

示例 1:
输入:
    2
   / \
  1   3

输出:
1

示例 2:
输入:
        1
       / \
      2   3
     /   / \
    4   5   6
       /
      7

输出:
7

分析

这虽然是一道中等题,但讲真的难度比较一般...
首先,最简单的应该是BFS逐层遍历

  1. 我们创建一个空列表,用于记录每行的第一个val
  2. 然后创建一个队列,root入队,开始while循环
  3. 每行的第一个节点入队,判断第一个方式为比较index与列表的长度是否相等
  4. 知道队列为空时,终止循环,pop列表最后一个数值即可。

那么,这道题用DFS同样很简单

  1. 为了练习,这次我们使用一个字典保存
  2. 同样的递归遍历左子树和右子树
  3. 判断字典中是否包含该值,然后插入该值
  4. 由于是数字hash,所以其实是有序的,直接values.pop()即可。

解题-BFS:

from collections import deque

class Solution:
    def findBottomLeftValue(self, root):
        li, queue= [], deque([[root, 1]])
        while queue:
            for _ in range(len(queue)):
                child, index = queue.popleft()
                if len(li) < index:
                    li.append(child.val)
                index += 1
                if child.left:
                    queue.append([child.left, index])
                if child.right:
                    queue.append([child.right, index])
        return li.pop()

解题-DFS:

class Solution:
    def findBottomLeftValue(self, root):
        d = {}
        def dfs(child, index):
            if not child:
                return
            if index not in d:
                d[index] = child.val
            dfs(child.left, index + 1)
            dfs(child.right, index + 1)
        dfs(root, 1)
        return list(d.values()).pop()

欢迎关注我的公众号: 清风Python,带你每日学习Python算法刷题的同时,了解更多python小知识。

我的个人博客:https://qingfengpython.cn

力扣解题合集:https://github.com/BreezePython/AlgorithmMarkdown

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值