LeetCode 513. 找树左下角的值

119 阅读1分钟

题目地址(513. 找树左下角的值)

leetcode-cn.com/problems/fi…

题目描述

给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。

假设二叉树中至少有一个节点。

 

示例 1:

输入: root = [2,1,3]
输出: 1


示例 2:

输入: [1,2,3,4,null,5,6,null,null,7]
输出: 7


 

提示:

二叉树的节点个数的范围是 [1,104]
-231 <= Node.val <= 231 - 1 

思路

用迭代方式存储list然后遍历

代码

  • 语言支持:Python3

Python3 Code:


# 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: TreeNode) -> int:
        nodeList = [root]
        while len(nodeList)>0:
            lenght = len(nodeList)
            res = nodeList[0].val
            for _ in range(lenght):
                cur = nodeList.pop(0)
                if cur.left:
                    nodeList.append(cur.left)
                if cur.right:
                    nodeList.append(cur.right)
        return res



复杂度分析

令 n 为数组长度。

  • 时间复杂度:O(n)O(n)
  • 空间复杂度:O(n)O(n)