513. 找树左下角的值
给定一个二叉树,在树的最后一行找到最左边的值。
示例 1:
输入:
2
/ \
1 3
输出:
1
示例 2:
输入:
1
/ \
2 3
/ / \
4 5 6
/
7
输出:
7
注意: 您可以假设树(即给定的根节点)不为 NULL。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-bottom-left-tree-value
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
层次遍历
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def findBottomLeftValue(self, root: TreeNode) -> int: def levelOrder(root): if not root: return [] queue,res=[root],[] while queue: n=len(queue) res.append([]) for i in range(n): node=queue[i] res[-1].append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) queue=queue[n:] return res return levelOrder(root)[-1][0]
dfs
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def findBottomLeftValue(self, root: TreeNode) -> int: a = [root] res = root.val while a: p = [] res = a[0].val for c in a: if c.left: p.append(c.left) if c.right: p.append(c.right) a = p return res