All Nodes Distance K in Binary Tree

LeetCode Q 863 - All Nodes Distance K in Binary Tree

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:

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

Solution:

Two points to solve this problem:

  • Transform the tree tos a graph, essentially transfrom a directed graph to an un-directed graph.
  • BFS traverse the graph to find nodes with a distance K to a target node.

Code:

Map<TreeNode, Set<TreeNode>> graph;
public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {
  graph = new HashMap<>();
  buildsGraph(root);
  
  Set<TreeNode> seen = new HashSet<>();
  Queue<TreeNode> que = new LinkedList<>();
  List<Integer> res = new ArrayList<>();
  
  que.offer(target); seen.add(target);
  
  while (!que.isEmpty()) {
    if (K == 0) { 
      while (!que.isEmpty()) res.add(que.poll().val);
      return res;
    }
    
    int size = que.size();
    
    for (int i = 0; i < size; i++) {
      TreeNode curr = que.poll();
      for (TreeNode n: graph.get(curr)) {
        if (seen.contains(n)) continue;
        que.offer(n); seen.add(n);
      }
    }
    
    K--;
  }
  
  return res;
}

private void buildsGraph(TreeNode root) {
  if (root == null) return;
  
  graph.putIfAbsent(root, new HashSet<>());
  
  if (root.left != null) {
    graph.get(root).add(root.left);
    graph.putIfAbsent(root.left, new HashSet<>());
    graph.get(root.left).add(root);
  }
  
  if (root.right != null) {
    graph.get(root).add(root.right);
    graph.putIfAbsent(root.right, new HashSet<>());
    graph.get(root.right).add(root);
  }
  
  buildsGraph(root.left);
  buildsGraph(root.right);
}

   Reprint policy


《All Nodes Distance K in Binary Tree》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC