Skip to content

Commit f126f7a

Browse files
author
weiy
committed
find bottom left tree value BFS
1 parent 49638dd commit f126f7a

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed

BFS/FindBottomLeftTreeValue.py

+94
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
"""
2+
Given a binary tree, find the leftmost value in the last row of the tree.
3+
4+
Example 1:
5+
Input:
6+
7+
2
8+
/ \
9+
1 3
10+
11+
Output:
12+
1
13+
Example 2:
14+
Input:
15+
16+
1
17+
/ \
18+
2 3
19+
/ / \
20+
4 5 6
21+
/
22+
7
23+
24+
Output:
25+
7
26+
27+
返回最底层最左边的一个节点的值。
28+
29+
思路:
30+
31+
使用广度优先算法:
32+
1. 也可以用深度优先算法,不过广度优先的话所需代码更少,更好理解。
33+
2. 广度优先:
34+
1 遍历1
35+
/ \
36+
2 3 遍历 2 3
37+
/ / \
38+
4 5 6 遍历 4 5 6
39+
/
40+
7 遍历 7
41+
42+
深度优先:
43+
1 遍历1
44+
/ \
45+
2 3 遍历2 -> 4
46+
/ / \
47+
4 5 6 遍历 3 -> 5 -> 7,3 -> 6
48+
/
49+
7
50+
51+
3. 广度优先运用在此处是以「层」为概念的,遍历完一层,再遍历一层。
52+
由于是返回最左边,所以从右向左。
53+
用两个列表,一个存放本层所有节点,一个存放本层所有节点的下层所有节点。
54+
遍历完本层后合并存放下层的列表,如果没有节点则返回结果。
55+
遍历本层时遵从 right to left. 有值就保存为结果。
56+
57+
测试用例:
58+
59+
https://leetcode.com/problems/find-bottom-left-tree-value/description/
60+
61+
40ms beat 74%.
62+
63+
"""
64+
# Definition for a binary tree node.
65+
# class TreeNode(object):
66+
# def __init__(self, x):
67+
# self.val = x
68+
# self.left = None
69+
# self.right = None
70+
71+
class Solution(object):
72+
def findBottomLeftValue(self, root):
73+
"""
74+
:type root: TreeNode
75+
:rtype: int
76+
"""
77+
waiting_for_access = [root]
78+
new_waiting_for_access = []
79+
result = root.val
80+
81+
while 1:
82+
while waiting_for_access:
83+
node = waiting_for_access.pop()
84+
85+
if node.right:
86+
new_waiting_for_access.append(node.right)
87+
result = node.right.val
88+
if node.left:
89+
new_waiting_for_access.append(node.left)
90+
result = node.left.val
91+
if not new_waiting_for_access:
92+
return result
93+
waiting_for_access.extend(new_waiting_for_access[::-1])
94+
new_waiting_for_access = []

0 commit comments

Comments
 (0)