893. All Nodes Distance K in Binary Tree
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The core of the problem is to find all nodes in a binary tree that are exactly k edges away from a given target node. A standard binary tree node only has pointers to its left and right children, but not to its parent. To calculate the distance, which is the shortest path, we need to be able to traverse not only downwards to children but also upwards to the parent. This suggests we need a way to represent parent-child relationships as bidirectional connections.
Solution
All Nodes Distance K in Binary Tree in Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import collections
class Solution:
def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:
if k == 0:
return [target.val]
# Adjacency list to represent the tree as a graph.
adj = collections.defaultdict(list)
# Helper function to build the undirected graph (adjacency list).
def build_graph(node, parent):
if not node:
return
if parent:
# Add edges between parent and child.
adj[node].append(parent)
adj[parent].append(node)
# Recur for left and right children.
build_graph(node.left, node)
build_graph(node.right, node)
build_graph(root, None)
# BFS to find nodes at distance k.
queue = collections.deque([target])
visited = {target}
distance = 0
while queue and distance < k:
level_size = len(queue)
for _ in range(level_size):
current = queue.popleft()
# Check neighbors in the adjacency list.
for neighbor in adj[current]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
distance += 1
# The queue now contains all nodes at distance k.
return [node.val for node in queue]
All Nodes Distance K in Binary Tree in Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> distanceK(TreeNode root, TreeNode target, int k) {
// Adjacency list to represent the tree as a graph.
Map<TreeNode, List<TreeNode>> adj = new HashMap<>();
buildGraph(root, null, adj);
List<Integer> result = new ArrayList<>();
if (k == 0) {
result.add(target.val);
return result;
}
// BFS to find nodes at distance k.
Queue<TreeNode> queue = new LinkedList<>();
Set<TreeNode> visited = new HashSet<>();
queue.add(target);
visited.add(target);
int distance = 0;
while (!queue.isEmpty() && distance < k) {
int levelSize = queue.size();
for (int i = 0; i < levelSize; i++) {
TreeNode current = queue.poll();
// Check neighbors in the adjacency list.
for (TreeNode neighbor : adj.getOrDefault(current, new ArrayList<>())) {
if (!visited.contains(neighbor)) {
visited.add(neighbor);
queue.add(neighbor);
}
}
}
distance++;
}
// The queue now contains all nodes at distance k.
while (!queue.isEmpty()) {
result.add(queue.poll().val);
}
return result;
}
// Helper function to build the undirected graph (adjacency list).
private void buildGraph(TreeNode node, TreeNode parent, Map<TreeNode, List<TreeNode>> adj) {
if (node == null) return;
if (parent != null) {
// Add edges between parent and child.
adj.computeIfAbsent(node, x -> new ArrayList<>()).add(parent);
adj.computeIfAbsent(parent, x -> new ArrayList<>()).add(node);
}
// Recur for left and right children.
buildGraph(node.left, node, adj);
buildGraph(node.right, node, adj);
}
}
All Nodes Distance K in Binary Tree in C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {
// Adjacency list to represent the tree as a graph.
unordered_map<TreeNode*, vector<TreeNode*>> adj;
buildGraph(root, nullptr, adj);
vector<int> result;
if (k == 0) {
result.push_back(target->val);
return result;
}
// BFS to find nodes at distance k.
queue<TreeNode*> q;
unordered_set<TreeNode*> visited;
q.push(target);
visited.insert(target);
int distance = 0;
while (!q.empty() && distance < k) {
int levelSize = q.size();
for (int i = 0; i < levelSize; ++i) {
TreeNode* current = q.front();
q.pop();
// Check neighbors in the adjacency list.
if (adj.count(current)) {
for (TreeNode* neighbor : adj[current]) {
if (visited.find(neighbor) == visited.end()) {
visited.insert(neighbor);
q.push(neighbor);
}
}
}
}
distance++;
}
// The queue now contains all nodes at distance k.
while (!q.empty()) {
result.push_back(q.front()->val);
q.pop();
}
return result;
}
private:
// Helper function to build the undirected graph (adjacency list).
void buildGraph(TreeNode* node, TreeNode* parent, unordered_map<TreeNode*, vector<TreeNode*>>& adj) {
if (!node) return;
if (parent) {
// Add edges between parent and child.
adj[node].push_back(parent);
adj[parent].push_back(node);
}
// Recur for left and right children.
buildGraph(node->left, node, adj);
buildGraph(node->right, node, adj);
}
};
All Nodes Distance K in Binary Tree in TypeScript
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function distanceK(root: TreeNode | null, target: TreeNode | null, k: number): number[] {
if (!root || !target) {
return [];
}
// Adjacency list to represent the tree as a graph.
const adj = new Map<TreeNode, TreeNode[]>();
// Helper function to build the undirected graph (adjacency list).
function buildGraph(node: TreeNode | null, parent: TreeNode | null) {
if (!node) return;
if (parent) {
// Add edges between parent and child.
if (!adj.has(node)) adj.set(node, []);
if (!adj.has(parent)) adj.set(parent, []);
adj.get(node)!.push(parent);
adj.get(parent)!.push(node);
}
// Recur for left and right children.
buildGraph(node.left, node);
buildGraph(node.right, node);
}
buildGraph(root, null);
const result: number[] = [];
if (k === 0) {
result.push(target.val);
return result;
}
// BFS to find nodes at distance k.
const queue: TreeNode[] = [target];
const visited = new Set<TreeNode>([target]);
let distance = 0;
while (queue.length > 0 && distance < k) {
const levelSize = queue.length;
for (let i = 0; i < levelSize; i++) {
const current = queue.shift()!;
// Check neighbors in the adjacency list.
const neighbors = adj.get(current) || [];
for (const neighbor of neighbors) {
if (!visited.has(neighbor)) {
visited.add(neighbor);
queue.push(neighbor);
}
}
}
distance++;
}
// The queue now contains all nodes at distance k.
for (const node of queue) {
result.push(node.val);
}
return result;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.