forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
closest-leaf-in-a-binary-tree.py
44 lines (39 loc) · 1.27 KB
/
closest-leaf-in-a-binary-tree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Time: O(n)
# Space: O(n)
import collections
class Solution(object):
def findClosestLeaf(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
def traverse(node, neighbors, leaves):
if not node:
return
if not node.left and not node.right:
leaves.add(node.val)
return
if node.left:
neighbors[node.val].append(node.left.val)
neighbors[node.left.val].append(node.val)
traverse(node.left, neighbors, leaves)
if node.right:
neighbors[node.val].append(node.right.val)
neighbors[node.right.val].append(node.val)
traverse(node.right, neighbors, leaves)
neighbors, leaves = collections.defaultdict(list), set()
traverse(root, neighbors, leaves)
q, lookup = [k], set([k])
while q:
next_q = []
for u in q:
if u in leaves:
return u
for v in neighbors[u]:
if v in lookup:
continue
lookup.add(v)
next_q.append(v)
q = next_q
return 0