[Naive Approach] Using Recursive Traversal (DFS) - O(n) time and O(h) Space
The idea is to use a recursive approach to find all nodes at a specified distance k from the root of a binary tree. or nodes at greater distances, the function recursively explores both left and right children, decrementing k with each call. And add the current node's data when k becomes 0.
Algorithm:
If root is NULL or k < 0, return
If k == 0, add current node’s value to result
Recur for left subtree with k - 1
Recur for right subtree with k - 1
C++
// c++ of find all nodes that are at distance // k from the root of a binary tree usign recursion.#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Function to collect nodes at distance// k from the root in a vectorvoidKdistanceUill(Node*root,intk,vector<int>&result){// If root is null and k is not zero return itif(root==NULL||k<0)return;// if k is zero then store the data and returnif(k==0){result.push_back(root->data);return;}// Make recursive call on left and right pointerKdistanceUill(root->left,k-1,result);KdistanceUill(root->right,k-1,result);}// Function to result all nodes at kth distance from rootvector<int>Kdistance(structNode*root,intk){vector<int>result;KdistanceUill(root,k,result);returnresult;}//Driver Codeintmain(){// Constructing the tree:// 8// / \ // 7 10// / / \ // 2 9 13Node*root=newNode(8);root->left=newNode(7);root->right=newNode(10);root->left->left=newNode(2);root->right->left=newNode(9);root->right->right=newNode(13);intk=2;vector<int>res=Kdistance(root,k);cout<<"Nodes at distance "<<k<<": ";for(intx:res){cout<<x<<" ";}cout<<endl;return0;}
Java
importjava.util.ArrayList;importjava.util.List;classNode{intdata;Nodeleft;Noderight;Node(intx){data=x;left=null;right=null;}}publicclassGfG{// Function to collect nodes at distance// k from the root in a vectorstaticvoidKdistanceUill(Noderoot,intk,List<Integer>result){// If root is null and k is not zero return itif(root==null||k<0)return;// if k is zero then store the data and returnif(k==0){result.add(root.data);return;}// Make recursive call on left and right pointerKdistanceUill(root.left,k-1,result);KdistanceUill(root.right,k-1,result);}// Function to result all nodes at kth distance from rootstaticList<Integer>Kdistance(Noderoot,intk){List<Integer>result=newArrayList<>();KdistanceUill(root,k,result);returnresult;}publicstaticvoidmain(String[]args){// Constructing the tree:// 8// / \// 7 10// / / \\// 2 9 13Noderoot=newNode(8);root.left=newNode(7);root.right=newNode(10);root.left.left=newNode(2);root.right.left=newNode(9);root.right.right=newNode(13);intk=2;List<Integer>res=Kdistance(root,k);System.out.print("Nodes at distance "+k+": ");for(intx:res){System.out.print(x+" ");}System.out.println();}}
Python
classNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to collect nodes at distance# k from the root in a vectordefKdistanceUill(root,k,result):# If root is null and k is not zero return itifrootisNoneork<0:return# if k is zero then store the data and returnifk==0:result.append(root.data)return# Make recursive call on left and right pointerKdistanceUill(root.left,k-1,result)KdistanceUill(root.right,k-1,result)# Function to result all nodes at kth distance from rootdefKdistance(root,k):result=[]KdistanceUill(root,k,result)returnresult# Driver Codeif__name__=='__main__':# Constructing the tree:# 8# / \# 7 10# / / \\# 2 9 13root=Node(8)root.left=Node(7)root.right=Node(10)root.left.left=Node(2)root.right.left=Node(9)root.right.right=Node(13)k=2res=Kdistance(root,k)print('Nodes at distance',k,':',end=' ')forxinres:print(x,end=' ')print()
C#
usingSystem;usingSystem.Collections.Generic;publicclassNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}publicclassGfG{// Function to collect nodes at distance// k from the root in a vectorstaticvoidKdistanceUill(Noderoot,intk,List<int>result){// If root is null and k is not zero return itif(root==null||k<0)return;// if k is zero then store the data and returnif(k==0){result.Add(root.data);return;}// Make recursive call on left and right pointerKdistanceUill(root.left,k-1,result);KdistanceUill(root.right,k-1,result);}// Function to result all nodes at kth distance from rootstaticList<int>Kdistance(Noderoot,intk){List<int>result=newList<int>();KdistanceUill(root,k,result);returnresult;}staticvoidMain(string[]args){// Constructing the tree:// 8// / \// 7 10// / / \\// 2 9 13Noderoot=newNode(8);root.left=newNode(7);root.right=newNode(10);root.left.left=newNode(2);root.right.left=newNode(9);root.right.right=newNode(13);intk=2;List<int>res=Kdistance(root,k);Console.Write("Nodes at distance "+k+": ");foreach(intxinres){Console.Write(x+" ");}Console.WriteLine();}}
JavaScript
classNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to collect nodes at distance// k from the root in a vectorfunctionKdistanceUill(root,k,result){// If root is null and k is not zero return itif(root===null||k<0)return;// if k is zero then store the data and returnif(k===0){result.push(root.data);return;}// Make recursive call on left and right pointerKdistanceUill(root.left,k-1,result);KdistanceUill(root.right,k-1,result);}// Function to result all nodes at kth distance from rootfunctionKdistance(root,k){letresult=[];KdistanceUill(root,k,result);returnresult;}// Driver Code// Constructing the tree:// 8// / \// 7 10// / / \\// 2 9 13letroot=newNode(8);root.left=newNode(7);root.right=newNode(10);root.left.left=newNode(2);root.right.left=newNode(9);root.right.right=newNode(13);letk=2;letres=Kdistance(root,k);console.log('Nodes at distance '+k+': '+res.join(' '));
Output
Nodes at distance 2: 2 9 13
Time Complexity: O(n) where n is number of nodes in the given binary tree. Space Complexity : O(h) where h is the height of binary tree.
[Better Approach] Using Queue - O(n) time and O(n) Space
This idea is based on line by line level order traversal. Start with an empty queue, enqueue the root, and set the level to 0. While the queue isn't empty, if the level equals k, store and return node values. For each node, dequeue it and enqueue its children. Increment the level after processing all nodes. return an empty list if no nodes are at distance k.
Algorithm:
Push root into the queue and set level or lvl = 0, then start level order traversal.
At each step, get current level size and check if lvl == k; if yes, store all node values and return.
Otherwise, remove each node and push its left and right children into the queue.
After processing the level, increment lvl and continue.
If the queue becomes empty before reaching k, return the empty result.
C++
// C++ code to implement the iterative // approach using a Queue#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};// Function to find all nodes at distance k from the rootvector<int>Kdistance(Node*root,intk){// If the root is NULL, return an empty vectorif(root==nullptr)return{};vector<int>result;// Create an empty queue for level order traversalqueue<Node*>q;q.push(root);intlvl=0;while(!q.empty()){// Get the number of nodes at the current levelintn=q.size();if(lvl==k){// Collect all nodes at this levelfor(inti=0;i<n;i++){Node*temp=q.front();result.push_back(temp->data);q.pop();}// Return the result as we've found // nodes at distance kreturnresult;}// Process all nodes at the current levelfor(inti=0;i<n;i++){Node*temp=q.front();q.pop();// If the left child exists, add it to the queueif(temp->left!=nullptr)q.push(temp->left);// If the right child exists, add it to the queueif(temp->right!=nullptr)q.push(temp->right);}// Move to the next levellvl+=1;}returnresult;}//Driver Codeintmain(){// Constructing the tree:// 8// / \ // 7 10// / / \ // 2 9 13Node*root=newNode(8);root->left=newNode(7);root->right=newNode(10);root->left->left=newNode(2);root->right->left=newNode(9);root->right->right=newNode(13);intk=2;vector<int>res=Kdistance(root,k);cout<<"Nodes at distance "<<k<<": ";for(intx:res){cout<<x<<" ";}cout<<endl;return0;}
Java
importjava.util.LinkedList;importjava.util.Queue;importjava.util.ArrayList;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}publicclassGfG{// Function to find all nodes at distance k from the rootpublicstaticArrayList<Integer>Kdistance(Noderoot,intk){// If the root is NULL, return an empty ArrayListif(root==null)returnnewArrayList<>();ArrayList<Integer>result=newArrayList<>();// Create an empty queue for level order traversalQueue<Node>q=newLinkedList<>();q.add(root);intlvl=0;while(!q.isEmpty()){// Get the number of nodes at the current levelintn=q.size();if(lvl==k){// Collect all nodes at this levelfor(inti=0;i<n;i++){Nodetemp=q.poll();result.add(temp.data);}// Return the result as we've found nodes at distance kreturnresult;}// Process all nodes at the current levelfor(inti=0;i<n;i++){Nodetemp=q.poll();// If the left child exists, add it to the queueif(temp.left!=null)q.add(temp.left);// If the right child exists, add it to the queueif(temp.right!=null)q.add(temp.right);}// Move to the next levellvl+=1;}returnresult;}//Driver Codepublicstaticvoidmain(String[]args){// Constructing the tree:// 8// / \// 7 10// / / \// 2 9 13Noderoot=newNode(8);root.left=newNode(7);root.right=newNode(10);root.left.left=newNode(2);root.right.left=newNode(9);root.right.right=newNode(13);intk=2;ArrayList<Integer>res=Kdistance(root,k);System.out.print("Nodes at distance "+k+": ");for(intx:res){System.out.print(x+" ");}System.out.println();}}
Python
fromcollectionsimportdequeclassNode:def__init__(self,x):self.data=xself.left=self.right=None# Function to find all nodes at distance k from the rootdefKdistance(root,k):# If the root is None, return an empty listifrootisNone:return[]result=[]# Create an empty queue for level order traversalq=deque([root])lvl=0whileq:# Get the number of nodes at the current leveln=len(q)iflvl==k:# Collect all nodes at this levelfor_inrange(n):temp=q.popleft()result.append(temp.data)# Return the result as we've found nodes at distance kreturnresult# Process all nodes at the current levelfor_inrange(n):temp=q.popleft()# If the left child exists, add it to the queueiftemp.leftisnotNone:q.append(temp.left)# If the right child exists, add it to the queueiftemp.rightisnotNone:q.append(temp.right)# Move to the next levellvl+=1returnresult#Driver Codeif__name__=='__main__':# Constructing the tree:# 8# / \# 7 10# / / \# 2 9 13root=Node(8)root.left=Node(7)root.right=Node(10)root.left.left=Node(2)root.right.left=Node(9)root.right.right=Node(13)k=2res=Kdistance(root,k)print("Nodes at distance ",k,": ",end="")forxinres:print(x,end=" ")print()
C#
usingSystem;usingSystem.Collections.Generic;publicclassNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}publicclassGfG{// Function to find all nodes at distance k from the rootpublicstaticList<int>Kdistance(Noderoot,intk){// If the root is NULL, return an empty listif(root==null)returnnewList<int>();List<int>result=newList<int>();// Create an empty queue for level order traversalQueue<Node>q=newQueue<Node>();q.Enqueue(root);intlvl=0;while(q.Count>0){// Get the number of nodes at the current levelintn=q.Count;if(lvl==k){// Collect all nodes at this levelfor(inti=0;i<n;i++){Nodetemp=q.Dequeue();result.Add(temp.data);}// Return the result as we've found nodes at distance kreturnresult;}// Process all nodes at the current levelfor(inti=0;i<n;i++){Nodetemp=q.Dequeue();// If the left child exists, add it to the queueif(temp.left!=null)q.Enqueue(temp.left);// If the right child exists, add it to the queueif(temp.right!=null)q.Enqueue(temp.right);}// Move to the next levellvl+=1;}returnresult;}//Driver CodepublicstaticvoidMain(){// Constructing the tree:// 8// / \// 7 10// / / \\// 2 9 13Noderoot=newNode(8);root.left=newNode(7);root.right=newNode(10);root.left.left=newNode(2);root.right.left=newNode(9);root.right.right=newNode(13);intk=2;List<int>res=Kdistance(root,k);Console.Write("Nodes at distance "+k+": ");for(intx=0;x<res.Count;x++){Console.Write(res[x]+" ");}Console.WriteLine();}}
JavaScript
classNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to find all nodes at distance k from the rootfunctionKdistance(root,k){// If the root is NULL, return an empty arrayif(root===null)return[];letresult=[];// Create an empty queue for level order traversalletq=[];q.push(root);letlvl=0;while(q.length>0){// Get the number of nodes at the current levelletn=q.length;if(lvl===k){// Collect all nodes at this levelfor(leti=0;i<n;i++){lettemp=q.shift();result.push(temp.data);}// Return the result as we've found nodes at distance kreturnresult;}// Process all nodes at the current levelfor(leti=0;i<n;i++){lettemp=q.shift();// If the left child exists, add it to the queueif(temp.left!==null)q.push(temp.left);// If the right child exists, add it to the queueif(temp.right!==null)q.push(temp.right);}// Move to the next levellvl+=1;}returnresult;}//Driver Code// Constructing the tree:// 8// / \// 7 10// / / \\// 2 9 13letroot=newNode(8);root.left=newNode(7);root.right=newNode(10);root.left.left=newNode(2);root.right.left=newNode(9);root.right.right=newNode(13);letk=2;letres=Kdistance(root,k);console.log(`Nodes at distance ${k}:`);for(letxofres){process.stdout.write(`${x} `);}console.log();
Output
Nodes at distance 2: 2 9 13
Time Complexity: O(n) where n is number of nodes in the given binary tree. Space Complexity: O(n)
[Expected Approach] Using Stack - O(n) time and O(n) Space
Push root with level 0 into stack and start traversal.
Pop top element, if node is NULL, continue.
If its level equals k, add node value to result.
Otherwise, push the right child with level + 1, then the left child with level + 1.
Repeat until the stack becomes empty and return the result.
C++
// C++ code to implement the iterative // approach using a stack#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};// Function to perform iterative DFS traversal and find all// nodes at distance Kvector<int>Kdistance(structNode*root,intk){vector<int>result;stack<pair<Node*,int>>stk;stk.push({root,0});while(!stk.empty()){Node*curr=stk.top().first;intlevel=stk.top().second;stk.pop();if(curr==nullptr){continue;}// If the current node is at distance K from the// root, add its data to the resultif(level==k){result.push_back(curr->data);}// Push the right child onto the stack with its// level incremented by 1stk.push({curr->right,level+1});// Push the left child onto the stack with its level// incremented by 1stk.push({curr->left,level+1});}returnresult;}//Driver Codeintmain(){// Constructing the tree:// 8// / \ // 7 10// / / \ // 2 9 13Node*root=newNode(8);root->left=newNode(7);root->right=newNode(10);root->left->left=newNode(2);root->right->left=newNode(9);root->right->right=newNode(13);intk=2;vector<int>res=Kdistance(root,k);cout<<"Nodes at distance "<<k<<": ";for(intx:res){cout<<x<<" ";}cout<<endl;return0;}
Java
importjava.util.ArrayList;importjava.util.Stack;classNode{publicintdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}publicclassGfG{// Function to perform iterative DFS traversal and find all// nodes at distance KstaticArrayList<Integer>Kdistance(Noderoot,intk){ArrayList<Integer>result=newArrayList<>();Stack<Pair>stk=newStack<>();stk.push(newPair(root,0));while(!stk.isEmpty()){Pairp=stk.pop();Nodecurr=p.first;intlevel=p.second;if(curr==null){continue;}// If the current node is at distance K from the// root, add its data to the resultif(level==k){result.add(curr.data);}// Push the right child onto the stack with its// level incremented by 1stk.push(newPair(curr.right,level+1));// Push the left child onto the stack with its level// incremented by 1stk.push(newPair(curr.left,level+1));}returnresult;}publicstaticvoidmain(String[]args){// Constructing the tree:// 8// / \// 7 10// / / \\// 2 9 13Noderoot=newNode(8);root.left=newNode(7);root.right=newNode(10);root.left.left=newNode(2);root.right.left=newNode(9);root.right.right=newNode(13);intk=2;ArrayList<Integer>res=Kdistance(root,k);System.out.print("Nodes at distance "+k+": ");for(intx:res){System.out.print(x+" ");}System.out.println();}// Helper class to store node and its levelstaticclassPair{Nodefirst;intsecond;Pair(Nodefirst,intsecond){this.first=first;this.second=second;}}}
Python
classNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to perform iterative DFS traversal and find all# nodes at distance KdefKdistance(root,k):result=[]stk=[(root,0)]whilestk:curr,level=stk.pop()ifcurrisNone:continue# If the current node is at distance K from the# root, add its data to the resultiflevel==k:result.append(curr.data)# Push the right child onto the stack with its# level incremented by 1stk.append((curr.right,level+1))# Push the left child onto the stack with its level# incremented by 1stk.append((curr.left,level+1))returnresult#Driver Code# Constructing the tree:# 8# / \# 7 10# / / \\# 2 9 13root=Node(8)root.left=Node(7)root.right=Node(10)root.left.left=Node(2)root.right.left=Node(9)root.right.right=Node(13)k=2res=Kdistance(root,k)print('Nodes at distance',k,':',' '.join(map(str,res)))
C#
usingSystem;usingSystem.Collections.Generic;publicclassNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}publicclassGfG{// Function to perform iterative DFS traversal and find all// nodes at distance KpublicstaticList<int>Kdistance(Noderoot,intk){List<int>result=newList<int>();Stack<(Node,int)>stk=newStack<(Node,int)>();stk.Push((root,0));while(stk.Count>0){var(curr,level)=stk.Pop();if(curr==null){continue;}// If the current node is at distance K from the// root, add its data to the resultif(level==k){result.Add(curr.data);}// Push the right child onto the stack with its// level incremented by 1stk.Push((curr.right,level+1));// Push the left child onto the stack with its level// incremented by 1stk.Push((curr.left,level+1));}returnresult;}publicstaticvoidMain(){// Constructing the tree:// 8// / \// 7 10// / / \\// 2 9 13Noderoot=newNode(8);root.left=newNode(7);root.right=newNode(10);root.left.left=newNode(2);root.right.left=newNode(9);root.right.right=newNode(13);intk=2;List<int>res=Kdistance(root,k);Console.Write("Nodes at distance "+k+": ");foreach(intxinres){Console.Write(x+" ");}Console.WriteLine();}}
JavaScript
classNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to perform iterative DFS traversal and find all// nodes at distance KfunctionKdistance(root,k){letresult=[];letstk=[];stk.push([root,0]);while(stk.length>0){let[curr,level]=stk.pop();if(curr===null){continue;}// If the current node is at distance K from the// root, add its data to the resultif(level===k){result.push(curr.data);}// Push the right child onto the stack with its// level incremented by 1stk.push([curr.right,level+1]);// Push the left child onto the stack with its level// incremented by 1stk.push([curr.left,level+1]);}returnresult;}//Driver Code// Constructing the tree:// 8// / \// 7 10// / / \\// 2 9 13letroot=newNode(8);root.left=newNode(7);root.right=newNode(10);root.left.left=newNode(2);root.right.left=newNode(9);root.right.right=newNode(13);letk=2;letres=Kdistance(root,k);console.log('Nodes at distance '+k+':'+res.join(' '));
Output
Nodes at distance 2: 2 9 13
Time Complexity: O(n) where n is the number of nodes in tree. Auxiliary Space: O(n)