Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Home
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
â–²455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets

Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
â–²455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
â–²455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
â–²455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Back to Problems

863. All Nodes Distance K in Binary Tree

Medium65.3% Acceptance
Hash TableTreeDepth-First Search
Asked by:
Amazon
ProblemSolutions (11)VideosCompanies (19)Notes

Problem Statement

Given the root of a binary tree, the value of a target node target, and an integer k, return an array of the values of all nodes that have a distance k from the target node.

You can return the answer 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.

Example 2:

Input: root = [1], target = 1, k = 3
Output: []

Constraints:

  • The number of nodes in the tree is in the range [1, 500].
  • 0 <= Node.val <= 500
  • All the values Node.val are unique.
  • target is the value of one of the nodes in the tree.
  • 0 <= k <= 1000
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
â–²455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
A
G
Google
F
Facebook
M
Microsoft
F
Flipkart
+14

Approach

In #863 All Nodes Distance K in Binary Tree, the goal is to find all nodes that are exactly K edges away from a given target node. Since binary tree nodes do not normally store references to their parents, a common strategy is to first convert the tree into an undirected structure.

One effective approach is to perform a DFS traversal to build a parent mapping using a HashMap. This allows movement both downward (to children) and upward (to parent). After building this map, a Breadth-First Search (BFS) starting from the target node explores neighbors level by level until distance K is reached. Nodes discovered at that level form the answer.

An alternative idea is a recursive DFS that calculates the distance from the target while propagating results up the tree. Both strategies ensure every node is visited at most once, leading to efficient performance.

Complexity

ApproachTime ComplexitySpace Complexity
BFS with Parent Hash MapO(N)O(N)
DFS Distance PropagationO(N)O(N)

Video Solution Available

take U forward

View all video solutions

Solutions (11)

Breadth-First Search (BFS) using Parent Map

In this method, we first traverse the tree to establish a mapping of each node to its parent. This will allow us to easily move upwards in the tree. We then perform a BFS starting from the target node to explore all nodes at distance K. Using a queue to explore nodes level by level ensures we can track the distance from the target correctly.

Time Complexity: O(N), where N is the number of nodes, since each node is visited once. Space Complexity: O(N) for storing the parent map and the queue.

CC++JavaPythonC#JavaScript
1#include <stdio.h>
2#include <stdlib.h>
3#include <stdbool.h>
4#include <string.h>
5
6// Define the TreeNode structure

















Explanation

This C solution first constructs a parent map using DFS to track each node's parent. It then uses BFS to explore nodes at increasing distances from the target node, utilizing a queue to maintain nodes and their distances. The visited array prevents cycles in the tree traversal.

Depth-First Search (DFS) with Backtracking

In this method, we perform a DFS from the root to find the path to the target node while also tracking parents of each node. We then use this path to initiate DFS from the target node in all possible directions (left, right, up) to find nodes that are K distance away.

Time Complexity: O(N), traversing the tree requires visiting each node once. Space Complexity: O(N) for the parent map and the recursion call stack.

C++JavaPythonC#JavaScript
1#include <iostream>
2#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

void findChildrenAtDistance(TreeNode* node, int K, vector<int>& result, unordered_set<TreeNode*>& visited) {
    if (!node || visited.count(node)) return;
    if (K == 0) {
        result.push_back(node->val);
        return;
    }
    visited.insert(node);
    findChildrenAtDistance(node->left, K - 1, result, visited);
    findChildrenAtDistance(node->right, K - 1, result, visited);
    visited.erase(node);
}

bool findTargetAndParents(TreeNode* root, TreeNode* target, unordered_map<TreeNode*, TreeNode*>& parentMap) {
    if (!root) return false;
    if (root == target) return true;
    parentMap[root->left] = root;
    if (findTargetAndParents(root->left, target, parentMap)) return true;
    parentMap[root->right] = root;
    if (findTargetAndParents(root->right, target, parentMap)) return true;
    return false;
}

vector<int> distanceK(TreeNode* root, TreeNode* target, int K) {
    unordered_map<TreeNode*, TreeNode*> parentMap;
    vector<int> result;
    unordered_set<TreeNode*> visited;
    findTargetAndParents(root, target, parentMap);

    queue<pair<TreeNode*, int>> bfsQueue;
    bfsQueue.push({target, 0});
    visited.insert(target);

    while (!bfsQueue.empty()) {
        auto [node, dist] = bfsQueue.front(); bfsQueue.pop();

        if (dist == K) result.push_back(node->val);

        for (TreeNode* neighbor : {node->left, node->right, parentMap[node]}) {
            if (neighbor && !visited.count(neighbor)) {
                visited.insert(neighbor);
                bfsQueue.push({neighbor, dist + 1});
            }
        }
    }

    return result;
}

Video Solutions

Watch expert explanations and walkthroughs

L30. Print all the Nodes at a distance of K in Binary Tree | C++ | Java

take U forward
17:42250,522 views

Asked By Companies

19 companies
A
Amazon
G
Google
F
Facebook
M
Microsoft
F
Flipkart
S
Samsung
P
PayTM
U
Uber
A
Apple
G
Goldman Sachs
N
Naukri
T
Tower Research Capital
M
Morgan Stanley
T
Twilio
D
Drawinbox
N
Nutanix
B
BYJUS
F
Flash Tech
J
Josh Technologies

Prepare for Interviews

Practice problems asked by these companies to ace your technical interviews.

Explore More Problems

Notes

Personal Notes

Jot down your thoughts, approach, and key learnings

0 characters

Similar Problems

Construct Binary Tree from Preorder and Inorder TraversalMedium
Construct Binary Tree from Inorder and Postorder TraversalMedium
Binary Tree Vertical Order TraversalMedium
Most Frequent Subtree SumMedium
More similar problems

Related Topics

Hash TableTreeDepth-First SearchBreadth-First SearchBinary Tree

Problem Stats

Acceptance Rate65.3%
DifficultyMedium
Companies19

Practice on LeetCode

Solve with full IDE support and test cases

Solve Now

Frequently Asked Questions

Can DFS be used to solve All Nodes Distance K in Binary Tree?

Yes, DFS can be used by recursively computing the distance from the target node and propagating that information up the tree. When the recursion detects nodes at the required distance, they are added to the result list.

Is All Nodes Distance K in Binary Tree asked in FAANG interviews?

Yes, this problem or similar tree-distance variations have appeared in interviews at top tech companies. It tests understanding of tree traversal, graph conversion, and BFS/DFS problem-solving techniques.

What data structure is best for All Nodes Distance K in Binary Tree?

A hash map is typically used to store parent references for each node. Combined with a queue for BFS and a visited set to prevent revisiting nodes, these structures make traversal efficient and manageable.

What is the optimal approach for All Nodes Distance K in Binary Tree?

A common optimal approach is to build a parent pointer map using DFS and then run BFS from the target node. This allows traversal to both children and the parent, effectively treating the tree like an undirected graph. BFS stops once the distance reaches K.

7
struct
TreeNode
{
8
int
val
;
9
struct
TreeNode
*
left
;
10
struct
TreeNode
*
right
;
11
}
;
12
13
// A node in the queue
14
struct
QueueNode
{
15
struct
TreeNode
*
node
;
16
int
distance
;
17
}
;
18
19
// Create a new tree node
20
struct
TreeNode
*
newTreeNode
(
int
val
)
{
21
struct
TreeNode
*
node
=
(
struct
TreeNode
*
)
malloc
(
sizeof
(
struct
TreeNode
)
)
;
22
node
->
val
=
val
;
23
node
->
left
=
node
->
right
=
NULL
;
24
return
node
;
25
}
26
27
// A simple queue implementation
28
#
define
MAX_QUEUE_SIZE
1000
29
typedef
struct
{
30
struct
QueueNode
data
[
MAX_QUEUE_SIZE
]
;
31
int
front
,
rear
;
32
}
Queue
;
33
34
void
initQueue
(
Queue
*
q
)
{
35
q
->
front
=
q
->
rear
=
0
;
36
}
37
38
bool
isQueueEmpty
(
Queue
*
q
)
{
39
return
q
->
front
==
q
->
rear
;
40
}
41
42
void
enqueue
(
Queue
*
q
,
struct
TreeNode
*
node
,
int
distance
)
{
43
q
->
data
[
q
->
rear
]
.
node
=
node
;
44
q
->
data
[
q
->
rear
]
.
distance
=
distance
;
45
q
->
rear
++
;
46
}
47
48
struct
QueueNode
dequeue
(
Queue
*
q
)
{
49
return
q
->
data
[
q
->
front
++
]
;
50
}
51
52
// Helper function for DFS that creates a map from node value to parent node
53
void
populateParentMap
(
struct
TreeNode
*
root
,
struct
TreeNode
*
parent
,
struct
TreeNode
*
*
parentMap
)
{
54
if
(
root
==
NULL
)
return
;
55
parentMap
[
root
->
val
]
=
parent
;
56
populateParentMap
(
root
->
left
,
root
,
parentMap
)
;
57
populateParentMap
(
root
->
right
,
root
,
parentMap
)
;
58
}
59
60
// BFS to find all nodes at distance K
61
void
findNodesAtDistance
(
struct
TreeNode
*
target
,
int
K
,
struct
TreeNode
*
*
parentMap
,
int
*
result
,
int
*
returnSize
)
{
62
Queue q
;
63
initQueue
(
&
q
)
;
64
bool visited
[
501
]
=
{
false
}
;
65
enqueue
(
&
q
,
target
,
0
)
;
66
visited
[
target
->
val
]
=
true
;
67
68
while
(
!
isQueueEmpty
(
&
q
)
)
{
69
struct
QueueNode
current
=
dequeue
(
&
q
)
;
70
struct
TreeNode
*
currNode
=
current
.
node
;
71
int
currDistance
=
current
.
distance
;
72
73
if
(
currDistance
==
K
)
{
74
result
[
(
*
returnSize
)
++
]
=
currNode
->
val
;
75
}
76
77
if
(
currDistance
>
K
)
break
;
78
79
// Check left child
80
if
(
currNode
->
left
&&
!
visited
[
currNode
->
left
->
val
]
)
{
81
enqueue
(
&
q
,
currNode
->
left
,
currDistance
+
1
)
;
82
visited
[
currNode
->
left
->
val
]
=
true
;
83
}
84
85
// Check right child
86
if
(
currNode
->
right
&&
!
visited
[
currNode
->
right
->
val
]
)
{
87
enqueue
(
&
q
,
currNode
->
right
,
currDistance
+
1
)
;
88
visited
[
currNode
->
right
->
val
]
=
true
;
89
}
90
91
// Check parent
92
struct
TreeNode
*
parent
=
parentMap
[
currNode
->
val
]
;
93
if
(
parent
&&
!
visited
[
parent
->
val
]
)
{
94
enqueue
(
&
q
,
parent
,
currDistance
+
1
)
;
95
visited
[
parent
->
val
]
=
true
;
96
}
97
}
98
}
99
100
int
*
distanceK
(
struct
TreeNode
*
root
,
struct
TreeNode
*
target
,
int
K
,
int
*
returnSize
)
{
101
struct
TreeNode
*
parentMap
[
501
]
=
{
NULL
}
;
102
int
*
result
=
malloc
(
500
*
sizeof
(
int
)
)
;
103
*
returnSize
=
0
;
104
105
populateParentMap
(
root
,
NULL
,
parentMap
)
;
106
findNodesAtDistance
(
target
,
K
,
parentMap
,
result
,
returnSize
)
;
107
108
return
result
;
109
}
110
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

Explanation

In this C++ implementation, we first fill a parent map while searching the target node. Then initiate a DFS from the target node in all directions, considering kids and parents. We backtrack to ensure each node is only visited once.