代码改变世界

[Leetcode] 863. All Nodes Distance K in Binary Tree_ Medium tag: BFS, Amazon

2018-07-03 09:35  Johnson_强生仔仔  阅读(771)  评论(0编辑  收藏  举报

We are given a binary tree (with root node root), a target node, and an integer value `K`.

Return a list of the values of all nodes that have a distance K from the target node.  The answer can be returned in any order.

 

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 2
Output: [7,4,1]
Explanation: 
The nodes that are a distance 2 from the target node (with value 5)
have values 7, 4, and 1.

Note that the inputs "root" and "target" are actually TreeNodes.
The descriptions of the inputs above are just serializations of these objects.

Note:

  1. The given tree is non-empty.
  2. Each node in the tree has unique values 0 <= node.val <= 500.
  3. The target node is a node in the tree.
  4. 0 <= K <= 1000.

 

经典的BFS, 其实跟之前做的employee importance很像, 只不过这个是tree, 那个是已经做好的列表, 但是我们可以用helper函数来讲tree 转换为一个undirected graph, 就是一个dictionary, 然后就用经典的BFS, 只不过append queue时, 要append进去id 和当前的distance. 注意一点的是edge case, k == 0, return [target.val], 其他时候是不包括target.val的.不过因为最开始visited已经有了target.val, 所以好像可以将判断node != target.val去掉. 经过验证, 确实是不需要这一步了. 

1. constraints

  1) tree not empty

  2) node.val is unique

  3) target always in tree

  4) 0 <= K <= 1000, edge case, K== 0 , 直接return target.val

 

2. ideas

 

   BFS :     T: O(n)     S: O(n)   n: number of nodes

1. edge

2. 将tree 转换为dictionary

3. 用常规的BFS的做法, 只不过append queue时, 要append进去id 和当前的distance.

 

3. code

 1 class Solution:
 2     def distancek(self, root, target, K):
 3         if K == 0: return [target.val]
 4         helper(root):
 5             if root:
 6                 if root.left:
 7                     d[root.val].add(root.left.val)
 8                     d[root.left.val].add(root.val)
 9                     helper(root.left)
10                 if root.right:
11                     d[root.val].add(root.right.val)
12                     d[root.right.val].add(root.val)
13                     helper(root.right)
14         d= collections.defaultdict(set)
15         helper(root)
16         queue, visited, ans = collections.deque([(target.val, 0)]), set([target.val]), [] # notice 不能直接用set(target.val), 因为要用iterable的parameter
17         while queue:
18             node, dis = queue.popleft()
19             if dis == K:
20                 ans.append(node)
21             elif dis < K:
22                 for each in d[node]:
23                     if each not in visited:
24                         queue.append((each, dis+1))
25                         visited.add(each)
26         return ans

 

4. test cases

用例子里面的cases即可.