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.


这道题 是 给我们一颗二叉树的根节点,让我们找到最后一层的最左边的节点。
绞尽脑汁之后,利用二维数组把每个节点和所在层次扒下来了,但是还是太麻烦。看了其他大神的思路豁然开朗!

大神的思路是:从右向左广度优先遍历!! 最后一个节点就是我们要的结果!!
献上我的代码:
 1 # Definition for a binary tree node.
 2 # class TreeNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution(object):
 9     def findBottomLeftValue(self, root):
10         """
11         :type root: TreeNode
12         :rtype: int
13         """
14         q = [root]
15         while q:
16             node = q.pop(0)
17             if node.right is not None:
18                 q.append(node.right)
19             if node.left is not None:
20                 q.append(node.left)
21         return node.val

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值