首页 > 其他 > 详细

All Nodes Distance K in Binary Tree

时间:2020-02-03 09:39:15      阅读:64      评论:0      收藏: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.

分析:先把tree转成graph,然后bfs。
 1 class Solution {
 2     Map<TreeNode, List<TreeNode>> map = new HashMap();
 3     
 4     public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {
 5         List<Integer> res = new ArrayList<> ();
 6         if (root == null || K < 0) return res;
 7         
 8         buildGraphFromTree(root, null); 
 9         if (!map.containsKey(target)) return res;
10         
11         Set<TreeNode> visited = new HashSet<>();
12         Queue<TreeNode> q = new LinkedList<>();
13         q.add(target);
14         visited.add(target);
15         while (!q.isEmpty()) {
16             int size = q.size();
17             if (K == 0) {
18                 while (!q.isEmpty()) {
19                     res.add(q.poll().val);
20                 }
21                 return res;
22             }
23             for (int i = 0; i < size; i++) {
24                 TreeNode node = q.poll();
25                 for (TreeNode neighbor : map.get(node)) {
26                     if (!visited.contains(neighbor)) {
27                         visited.add(neighbor);
28                         q.add(neighbor);
29                     }
30                 }
31             }
32             K--;
33         }
34         return res;
35     }
36     
37     private void buildGraphFromTree(TreeNode node, TreeNode parent) {
38         if (node != null) {
39             map.put(node, new ArrayList<TreeNode>());
40             if (parent != null) {
41                 map.get(node).add(parent);
42                 map.get(parent).add(node);
43             }
44             buildGraphFromTree(node.left, node);
45             buildGraphFromTree(node.right, node);
46         }
47     }    
48 }

 

All Nodes Distance K in Binary Tree

原文:https://www.cnblogs.com/beiyeqingteng/p/12254338.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!