Given a root of binary tree having n nodes and an integer k, return all nodes that are at distance k from the root (root is considered at distance 0 from itself). Nodes should be returned fromleft to right.
Examples:
Input: k = 0, root = [1, 3, 2]
Output: 1 Explanation: 1 is the only node which is 0 distance from the root 1.
Input: k = 3, root = [1, 2, N, N, 1, 5, 3]
Output: 5 3 Explanation: 5 and 3 are the nodes which are at distance 3 from the root 1, returned from left to right.
[Naive Approach] Recursive Traversal (DFS) - O(n) Time and O(h) Space
The idea is to recursively explores both left and right children, decrementing k with each call. And add the current node's data when k becomes 0.
Working of Approach:
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++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=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.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGFG{// Function to collect nodes at distance k from the rootvoidkdistanceUill(Noderoot,intk,ArrayList<Integer>result){// If root is null or k is negative, returnif(root==null||k<0)return;// If k is zero, store the node's dataif(k==0){result.add(root.data);return;}// Recursive calls on the left and right subtreeskdistanceUill(root.left,k-1,result);kdistanceUill(root.right,k-1,result);}// Function to return all nodes at distance k from the// rootArrayList<Integer>kdistance(Noderoot,intk){ArrayList<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;GFGobj=newGFG();ArrayList<Integer>res=obj.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
[Better Approach] Queue - O(n) Time and O(n) Space
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.
Working of Approach:
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++
#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;}intmain(){// 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.LinkedList;importjava.util.Queue;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;}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();}}
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+=1returnresultif__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;}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+": ");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
[Expected Approach] 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++
#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(Node*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.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGFG{// Helper class to store a node and its levelstaticclassPair{Nodenode;intlevel;Pair(Nodenode,intlevel){this.node=node;this.level=level;}}// Function to perform iterative DFS and find nodes at// distance KstaticArrayList<Integer>kdistance(Noderoot,intk){ArrayList<Integer>result=newArrayList<>();Stack<Pair>stk=newStack<>();stk.push(newPair(root,0));while(!stk.isEmpty()){Pairtop=stk.pop();Nodecurr=top.node;intlevel=top.level;if(curr==null)continue;// If the current node is at distance K, store// its dataif(level==k){result.add(curr.data);continue;}// Push the right child with its level// incremented by 1stk.push(newPair(curr.right,level+1));// Push the left child 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();}}
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# 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(" "));