Algo-Sim › Binary Trees & BST
All Nodes Distance K in Binary Tree
Medium · Binary Trees & BST · step through it in Java, Python and C++ on your own input
Record each node’s parent, then BFS outward from the target through children and parents; the queue after k rounds is the answer.
Problem
Given the root of a binary tree with distinct values, a target node in it, and an integer k, return the values of every node exactly k edges away from target, in any order. Edges may be walked in either direction.
Constraints
- 1 ≤ number of nodes ≤ 500
- All values are distinct
targetis in the tree- 0 ≤ k ≤ 1000
Edge cases to test
- k = 0: just the target
- k larger than the tree height
- The target is the root
Follow-up questions
- Why record parents?
- Distance k can go up through ancestors; parent links turn the tree into an undirected graph for BFS: O(n).
- Can you avoid the parent map?
- A DFS that returns the distance to the target lets each ancestor search its other subtree at k − d − 1.
Solution
Java
public List<Integer> distanceK(TreeNode root, TreeNode target, int k) {
Map<TreeNode, TreeNode> parent = new HashMap<>();
link(root, null, parent);
Queue<TreeNode> queue = new ArrayDeque<>(List.of(target));
Set<TreeNode> seen = new HashSet<>(List.of(target));
for (int dist = 0; dist < k && !queue.isEmpty(); dist++) {
for (int size = queue.size(); size > 0; size--) {
TreeNode node = queue.poll();
for (TreeNode next : new TreeNode[] {node.left, node.right, parent.get(node)}) {
if (next != null && seen.add(next)) queue.offer(next);
}
}
}
List<Integer> result = new ArrayList<>();
for (TreeNode node : queue) result.add(node.val);
return result;
}
private void link(TreeNode node, TreeNode from, Map<TreeNode, TreeNode> parent) {
if (node == null) return;
parent.put(node, from);
link(node.left, node, parent);
link(node.right, node, parent);
}Python
from collections import deque
def distance_k(root, target, k):
parent = {}
link(root, None, parent)
queue, seen = deque([target]), {target}
for _ in range(k):
if not queue:
break
for _ in range(len(queue)):
node = queue.popleft()
for nxt in (node.left, node.right, parent[node]):
if nxt and nxt not in seen:
seen.add(nxt)
queue.append(nxt)
return [node.val for node in queue]
def link(node, frm, parent):
if not node:
return
parent[node] = frm
link(node.left, node, parent)
link(node.right, node, parent)C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> distanceK(TreeNode *root, TreeNode *target, int k) {
unordered_map<TreeNode *, TreeNode *> parent;
link(root, nullptr, parent);
deque<TreeNode *> queue = {target};
unordered_set<TreeNode *> seen = {target};
for (int dist = 0; dist < k && !queue.empty(); dist++) {
for (int size = int(queue.size()); size > 0; size--) {
TreeNode *node = queue.front();
queue.pop_front();
for (TreeNode *next : {node->left, node->right, parent[node]}) {
if (next != nullptr && seen.insert(next).second)
queue.push_back(next);
}
}
}
vector<int> result;
for (TreeNode *node : queue)
result.push_back(node->val);
return result;
}
private:
void link(TreeNode *node, TreeNode *from, unordered_map<TreeNode *, TreeNode *> &parent) {
if (node == nullptr)
return;
parent[node] = from;
link(node->left, node, parent);
link(node->right, node, parent);
}
};
More Binary Trees & BST problems
- Preorder Traversal (Recursive) (Easy)
- Inorder Traversal (Recursive) (Easy)
- Postorder Traversal (Recursive) (Easy)
- Preorder Traversal (Iterative) (Easy)
- Inorder Traversal (Iterative) (Easy)
- Postorder Traversal (Iterative) (Easy)
- Binary Tree Level Order Traversal (Medium)
- Binary Tree Zigzag Level Order Traversal (Medium)
- Binary Tree Right Side View (Medium)
- Vertical Order Traversal of a Binary Tree (Hard)
- Maximum Depth of Binary Tree (Easy)
- Diameter of Binary Tree (Easy)
- Balanced Binary Tree (Easy)
- Invert Binary Tree (Easy)
- Flatten Binary Tree to Linked List (Medium)
- Same Tree (Easy)
- Symmetric Tree (Easy)
- Subtree of Another Tree (Easy)
- Path Sum (Easy)
- Path Sum II (Medium)
- Path Sum III (Medium)
- Count Good Nodes in Binary Tree (Medium)
- Lowest Common Ancestor of a Binary Tree (Medium)
- Kth Ancestor of a Tree Node (Hard)
- Validate Binary Search Tree (Medium)
- Search in a Binary Search Tree (Easy)
- Insert into a Binary Search Tree (Medium)
- Delete Node in a BST (Medium)
- Kth Smallest Element in a BST (Medium)
- Binary Search Tree Iterator (Medium)
- Convert Sorted Array to Binary Search Tree (Easy)
- AVL Tree Insert (Hard)
- Construct Binary Tree from Preorder and Inorder Traversal (Medium)
- Binary Tree Maximum Path Sum (Hard)
- Serialize and Deserialize Binary Tree (Hard)