leetcode算法: Find Bottom Left Tree Value

leetcode算法: Find Bottom Left Tree Value

Given a binary tree, find the leftmost value in the last row of the tree.

Example 1:
Input: 2
/ \
1 3 Output:
1
Example 2:
Input: 1
/ \
2 3
/ / \
4 5 6
/
7 Output:
7
Note: You may assume the tree (i.e., the given root node) is not NULL. 这道题 是 给我们一颗二叉树的根节点,让我们找到最后一层的最左边的节点。
绞尽脑汁之后,利用二维数组把每个节点和所在层次扒下来了,但是还是太麻烦。看了其他大神的思路豁然开朗! 大神的思路是:从右向左广度优先遍历!! 最后一个节点就是我们要的结果!!
献上我的代码:
 # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def findBottomLeftValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
q = [root]
while q:
node = q.pop(0)
if node.right is not None:
q.append(node.right)
if node.left is not None:
q.append(node.left)
return node.val
上一篇:keras&tensorflow+分布式训练︱实现简易视频内容问答框架


下一篇:【LeetCode】513. Find Bottom Left Tree Value 解题报告(Python & C++ & Java)