Advertisement
jinhuang1102

742. Closest Leaf in a Binary Tree

Mar 20th, 2019
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.74 KB | None | 0 0
  1. """
  2. 742. Closest Leaf in a Binary Tree
  3.  
  4. 树本身就是一个无向图,所以先建立一个无向图。这道题问的是叶节点,所以这道题的技巧是用一个set来维护所有的叶节点。之后再用BFS的时候就可以查找是否是叶节点。 之前自己就是卡在了不知道怎么寻找叶节点上面。
  5. """
  6. from collections import deque, defaultdict
  7.  
  8.  
  9. class Solution(object):
  10.     def connect(self, root, graph, leaves):
  11.         if not root:
  12.             return
  13.        
  14.         if not root.left and not root.right:    # 叶节点
  15.             leaves.add(root.val)       
  16.             return
  17.        
  18.         if root.left:
  19.             graph[root] = root.left
  20.             graph[root.left] = root
  21.             self.connect(root.left, graph, leaves)
  22.            
  23.         if root.right:
  24.             graph[root] = root.right
  25.             graph[root.right] = root
  26.             self.connect(root.right, graph, leaves)
  27.    
  28.     def findClosestLeaf(self, root, k):
  29.         """
  30.        :type root: TreeNode
  31.        :type k: int
  32.        :rtype: int
  33.        """
  34.         graph = defaultdict(list)        
  35.         leaves = set()                    # 运用set便于检索
  36.         self.connect(root, graph, leaves) # 建立无向图 and 把叶节点装进Set便于之后查找。
  37.        
  38.         visited = set()                   # visited
  39.        
  40.         q = deque()                       # BFS
  41.         q.append(k)
  42.         while q:
  43.             num = len(q)
  44.             for i in range(num):
  45.                 node = q.popleft()
  46.                 if node in leaves:
  47.                     return node
  48.                 if not node in visited:
  49.                     visited.add(node)
  50.                     q.extend(graph[node])
  51.  
  52.         return
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement