Given the root of a binary tree, the value of a target node, and an integer k, return all the nodes that are exactly k edges away from the target node. Return the node values in sorted order.
Note:
All node values are unique.
The target node is guaranteed to be present in the tree.
Examples:
Input: root = [1, 2, 3, 4, 5],target = 2, k = 2
Output: 3 Explanation: Nodes at a distance 2 from the given target node 2 is 3.
To find the distance between current node and target, we first find LCA of both and use the LCA.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};// Find the LCA of two nodes.Node*lca(Node*root,inta,intb){if(root==nullptr||root->data==a||root->data==b)returnroot;Node*left=lca(root->left,a,b);Node*right=lca(root->right,a,b);if(left&&right)returnroot;returnleft?left:right;}// Find distance of a node from the root.intfindDist(Node*root,inttarget){if(root==nullptr)return-1;if(root->data==target)return0;intleft=findDist(root->left,target);if(left!=-1)returnleft+1;intright=findDist(root->right,target);if(right!=-1)returnright+1;return-1;}// Find distance between two nodes.intdistance(Node*root,inta,intb){Node*ancestor=lca(root,a,b);intd1=findDist(ancestor,a);intd2=findDist(ancestor,b);returnd1+d2;}voidsolve(Node*root,Node*treeRoot,inttarget,intk,vector<int>&ans){if(root==nullptr)return;// Check if current node is at distance k from target.if(distance(treeRoot,root->data,target)==k)ans.push_back(root->data);solve(root->left,treeRoot,target,k,ans);solve(root->right,treeRoot,target,k,ans);}vector<int>kDistanceNodes(Node*root,inttarget,intk){vector<int>ans;solve(root,root,target,k,ans);// Sort the result.sort(ans.begin(),ans.end());returnans;}intmain(){// Create the binary tree:// 1// / \ // 2 3// / \ // 4 5Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);inttarget=2;intk=2;vector<int>ans=kDistanceNodes(root,target,k);for(intx:ans)cout<<x<<" ";return0;}
Java
importjava.util.ArrayList;importjava.util.Collections;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// Find the LCA of two nodes.staticNodelca(Noderoot,inta,intb){if(root==null||root.data==a||root.data==b)returnroot;Nodeleft=lca(root.left,a,b);Noderight=lca(root.right,a,b);if(left!=null&&right!=null)returnroot;returnleft!=null?left:right;}// Find distance of a node from the root.staticintfindDist(Noderoot,inttarget){if(root==null)return-1;if(root.data==target)return0;intleft=findDist(root.left,target);if(left!=-1)returnleft+1;intright=findDist(root.right,target);if(right!=-1)returnright+1;return-1;}// Find distance between two nodes.staticintdistance(Noderoot,inta,intb){Nodeancestor=lca(root,a,b);intd1=findDist(ancestor,a);intd2=findDist(ancestor,b);returnd1+d2;}staticvoidsolve(Noderoot,NodetreeRoot,inttarget,intk,ArrayList<Integer>ans){if(root==null)return;// Check if current node is at distance k from target.if(distance(treeRoot,root.data,target)==k)ans.add(root.data);solve(root.left,treeRoot,target,k,ans);solve(root.right,treeRoot,target,k,ans);}staticArrayList<Integer>kDistanceNodes(Noderoot,inttarget,intk){ArrayList<Integer>ans=newArrayList<>();solve(root,root,target,k,ans);// Sort the result.Collections.sort(ans);returnans;}publicstaticvoidmain(String[]args){// Create the binary tree:// 1// / \// 2 3// / \// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);inttarget=2;intk=2;ArrayList<Integer>ans=kDistanceNodes(root,target,k);for(intx:ans)System.out.print(x+" ");}}
Python
classNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Find the LCA of two nodes.deflca(root,a,b):ifrootisNoneorroot.data==aorroot.data==b:returnrootleft=lca(root.left,a,b)right=lca(root.right,a,b)ifleftandright:returnrootreturnleftifleftelseright# Find distance of a node from the root.deffindDist(root,target):ifrootisNone:return-1ifroot.data==target:return0left=findDist(root.left,target)ifleft!=-1:returnleft+1right=findDist(root.right,target)ifright!=-1:returnright+1return-1# Find distance between two nodes.defdistance(root,a,b):ancestor=lca(root,a,b)d1=findDist(ancestor,a)d2=findDist(ancestor,b)returnd1+d2defsolve(root,treeRoot,target,k,ans):ifrootisNone:return# Check if current node is at distance k from target.ifdistance(treeRoot,root.data,target)==k:ans.append(root.data)solve(root.left,treeRoot,target,k,ans)solve(root.right,treeRoot,target,k,ans)defkDistanceNodes(root,target,k):ans=[]solve(root,root,target,k,ans)# Sort the result.ans.sort()returnansif__name__=="__main__":# Create the binary tree:# 1# / \# 2 3# / \# 4 5root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)target=2k=2ans=kDistanceNodes(root,target,k)forxinans:print(x,end=" ")
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGFG{// Find the LCA of two nodes.staticNodelca(Noderoot,inta,intb){if(root==null||root.data==a||root.data==b)returnroot;Nodeleft=lca(root.left,a,b);Noderight=lca(root.right,a,b);if(left!=null&&right!=null)returnroot;returnleft!=null?left:right;}// Find distance of a node from the root.staticintfindDist(Noderoot,inttarget){if(root==null)return-1;if(root.data==target)return0;intleft=findDist(root.left,target);if(left!=-1)returnleft+1;intright=findDist(root.right,target);if(right!=-1)returnright+1;return-1;}// Find distance between two nodes.staticintdistance(Noderoot,inta,intb){Nodeancestor=lca(root,a,b);intd1=findDist(ancestor,a);intd2=findDist(ancestor,b);returnd1+d2;}staticvoidsolve(Noderoot,NodetreeRoot,inttarget,intk,List<int>ans){if(root==null)return;// Check if current node is at distance k from target.if(distance(treeRoot,root.data,target)==k)ans.Add(root.data);solve(root.left,treeRoot,target,k,ans);solve(root.right,treeRoot,target,k,ans);}publicstaticList<int>kDistanceNodes(Noderoot,inttarget,intk){List<int>ans=newList<int>();solve(root,root,target,k,ans);// Sort the result.ans.Sort();returnans;}publicstaticvoidMain(){// Create the binary tree:// 1// / \// 2 3// / \// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);inttarget=2;intk=2;List<int>ans=kDistanceNodes(root,target,k);foreach(intxinans)Console.Write(x+" ");}}
JavaScript
classNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Find the LCA of two nodes.functionlca(root,a,b){if(root===null||root.data===a||root.data===b)returnroot;letleft=lca(root.left,a,b);letright=lca(root.right,a,b);if(left&&right)returnroot;returnleft?left:right;}// Find distance of a node from the root.functionfindDist(root,target){if(root===null)return-1;if(root.data===target)return0;letleft=findDist(root.left,target);if(left!==-1)returnleft+1;letright=findDist(root.right,target);if(right!==-1)returnright+1;return-1;}// Find distance between two nodes.functiondistance(root,a,b){letancestor=lca(root,a,b);letd1=findDist(ancestor,a);letd2=findDist(ancestor,b);returnd1+d2;}functionsolve(root,treeRoot,target,k,ans){if(root===null)return;// Check if current node is at distance k from target.if(distance(treeRoot,root.data,target)===k)ans.push(root.data);solve(root.left,treeRoot,target,k,ans);solve(root.right,treeRoot,target,k,ans);}functionkDistanceNodes(root,target,k){letans=[];solve(root,root,target,k,ans);// Sort the result.ans.sort((a,b)=>a-b);returnans;}// Driver code// Create the binary tree:// 1// / \// 2 3// / \// 4 5letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);lettarget=2;letk=2;letans=kDistanceNodes(root,target,k);for(letxofans)process.stdout.write(x+" ");
Output
3
[Expected Approach - 1] Using Recursion - O(n log n) Time and O(h) Space
The idea is to traverse the binary tree using recursion to find the target node. Once the target is found, find all nodes at distance k in its left and right subtrees.
While returning through the path from the target to the root, check the opposite subtree (if target is present in left, then check right and vice versa) of each ancestor for nodes at the remaining distance, which is k - distance - 1.
Suppose the target is present in the left subtree of the current node:
To reach a node in the right subtree from the target:
Distance edges are used to reach the current node from the target.
One more edge is used to move from the current node to the right subtree.
Therefore, the remaining distance to search in the right subtree is: k - distance - 1
Similarly, if the target is present in the right subtree, we search the left subtree at distance k - distance - 1.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};// Find nodes at a given distance from root.voidfindNodes(Node*root,intdis,vector<int>&ans){if(root==nullptr)return;if(dis==0){ans.push_back(root->data);return;}findNodes(root->left,dis-1,ans);findNodes(root->right,dis-1,ans);}// Find the distance of target from the current node.intkDistanceRecur(Node*root,inttarget,intk,vector<int>&ans){if(root==nullptr)return-1;// If current node is target.if(root->data==target){findNodes(root,k,ans);return1;}intleft=kDistanceRecur(root->left,target,k,ans);// Target is present in the left subtree.if(left!=-1){if(k-left==0)ans.push_back(root->data);elsefindNodes(root->right,k-left-1,ans);returnleft+1;}intright=kDistanceRecur(root->right,target,k,ans);// Target is present in the right subtree.if(right!=-1){if(k-right==0)ans.push_back(root->data);elsefindNodes(root->left,k-right-1,ans);returnright+1;}return-1;}vector<int>kDistanceNodes(Node*root,inttarget,intk){vector<int>ans;kDistanceRecur(root,target,k,ans);// Sort the result.sort(ans.begin(),ans.end());returnans;}intmain(){// Create the binary tree:// 1// / \ // 2 3// / \ // 4 5Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);inttarget=2;intk=2;vector<int>ans=kDistanceNodes(root,target,k);for(intx:ans)cout<<x<<" ";return0;}
Java
importjava.util.ArrayList;importjava.util.Collections;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGFG{// Find nodes at a given distance from root.staticvoidfindNodes(Noderoot,intdis,ArrayList<Integer>ans){if(root==null)return;if(dis==0){ans.add(root.data);return;}findNodes(root.left,dis-1,ans);findNodes(root.right,dis-1,ans);}// Find the distance of target from the current node.staticintkDistanceRecur(Noderoot,inttarget,intk,ArrayList<Integer>ans){if(root==null)return-1;// If current node is target.if(root.data==target){findNodes(root,k,ans);return1;}intleft=kDistanceRecur(root.left,target,k,ans);// Target is present in the left subtree.if(left!=-1){if(k-left==0)ans.add(root.data);elsefindNodes(root.right,k-left-1,ans);returnleft+1;}intright=kDistanceRecur(root.right,target,k,ans);// Target is present in the right subtree.if(right!=-1){if(k-right==0)ans.add(root.data);elsefindNodes(root.left,k-right-1,ans);returnright+1;}return-1;}staticArrayList<Integer>kDistanceNodes(Noderoot,inttarget,intk){ArrayList<Integer>ans=newArrayList<>();kDistanceRecur(root,target,k,ans);// Sort the result.Collections.sort(ans);returnans;}publicstaticvoidmain(String[]args){// Create the binary tree:// 1// / \// 2 3// / \// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);inttarget=2;intk=2;ArrayList<Integer>ans=kDistanceNodes(root,target,k);for(intx:ans)System.out.print(x+" ");}}
Python
# Structure of Binary Tree NodeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Find nodes at a given distance from root.deffindNodes(root,dis,ans):ifrootisNoneordis<0:returnifdis==0:ans.append(root.data)returnfindNodes(root.left,dis-1,ans)findNodes(root.right,dis-1,ans)# Find the distance of target from the current node.defkDistanceRecur(root,target,k,ans):ifrootisNone:return-1# If current node is target.ifroot.data==target:findNodes(root,k,ans)return1left=kDistanceRecur(root.left,target,k,ans)# Target is present in the left subtree.ifleft!=-1:ifk-left==0:ans.append(root.data)else:findNodes(root.right,k-left-1,ans)returnleft+1right=kDistanceRecur(root.right,target,k,ans)# Target is present in the right subtree.ifright!=-1:ifk-right==0:ans.append(root.data)else:findNodes(root.left,k-right-1,ans)returnright+1return-1defkDistanceNodes(root,target,k):ans=[]kDistanceRecur(root,target,k,ans)# Sort the result.ans.sort()returnansif__name__=="__main__":# Create the binary tree:# 1# / \# 2 3# / \# 4 5root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)target=2k=2ans=kDistanceNodes(root,target,k)forxinans:print(x,end=" ")
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGFG{// Find nodes at a given distance from root.staticvoidfindNodes(Noderoot,intdis,List<int>ans){if(root==null)return;if(dis==0){ans.Add(root.data);return;}findNodes(root.left,dis-1,ans);findNodes(root.right,dis-1,ans);}// Find the distance of target from the current node.staticintkDistanceRecur(Noderoot,inttarget,intk,List<int>ans){if(root==null)return-1;// If current node is target.if(root.data==target){findNodes(root,k,ans);return1;}intleft=kDistanceRecur(root.left,target,k,ans);// Target is present in the left subtree.if(left!=-1){if(k-left==0)ans.Add(root.data);elsefindNodes(root.right,k-left-1,ans);returnleft+1;}intright=kDistanceRecur(root.right,target,k,ans);// Target is present in the right subtree.if(right!=-1){if(k-right==0)ans.Add(root.data);elsefindNodes(root.left,k-right-1,ans);returnright+1;}return-1;}staticList<int>kDistanceNodes(Noderoot,inttarget,intk){List<int>ans=newList<int>();kDistanceRecur(root,target,k,ans);// Sort the result.ans.Sort();returnans;}staticvoidMain(){// Create the binary tree:// 1// / \// 2 3// / \// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);inttarget=2;intk=2;List<int>ans=kDistanceNodes(root,target,k);foreach(intxinans)Console.Write(x+" ");}}
JavaScript
classNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Find nodes at a given distance from root.functionfindNodes(root,dis,ans){if(root===null)return;if(dis===0){ans.push(root.data);return;}findNodes(root.left,dis-1,ans);findNodes(root.right,dis-1,ans);}// Find the distance of target from the current node.functionkDistanceRecur(root,target,k,ans){if(root===null)return-1;// If current node is target.if(root.data===target){findNodes(root,k,ans);return1;}letleft=kDistanceRecur(root.left,target,k,ans);// Target is present in the left subtree.if(left!==-1){if(k-left===0)ans.push(root.data);elsefindNodes(root.right,k-left-1,ans);returnleft+1;}letright=kDistanceRecur(root.right,target,k,ans);// Target is present in the right subtree.if(right!==-1){if(k-right===0)ans.push(root.data);elsefindNodes(root.left,k-right-1,ans);returnright+1;}return-1;}functionkDistanceNodes(root,target,k){letans=[];kDistanceRecur(root,target,k,ans);// Sort the result.ans.sort((a,b)=>a-b);returnans;}// Driver code// Create the binary tree:// 1// / \// 2 3// / \// 4 5letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);lettarget=2;letk=2;letans=kDistanceNodes(root,target,k);for(letxofans)process.stdout.write(x+" ");
Output
3
[Expected Approach - 2] Using BFS with Parent Mapping - O(n log n) Time and O(n) Space
The idea is to store the parent of every node in a hash map so that we can move from the target node in all three directions: left child, right child, and parent. Then, perform Breadth First Search (BFS) from the target to find all nodes at distance k.
Note that we can do DFS as well once we have the parent mapping.
In a binary tree, we can normally move only from a node to its children. Therefore, a node outside the target's subtree cannot be reached directly.
Consider:
To make this upward movement possible, store the parent of every node:
4 -> 2
5 -> 2
2 -> 1
3 -> 1
Now, from any node, we can move to its left child, right child, or parent.
Start BFS from the target node with distance 0.
Move to the left child, right child, and parent.
Keep track of visited nodes to avoid visiting the same node again.
Process the tree level by level and increase the distance after each level.
When the distance becomes k, the nodes in the queue are exactly k edges away from the target.
Finally, sort the result.
C+
#include<bits/stdc++.h>usingnamespacestd;// Structure of Binary Tree NodeclassNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};unordered_map<Node*,Node*>par;// Build the parent mapping and locate the target nodeNode*markParents(Node*root,inttarget){Node*tar=nullptr;queue<Node*>q;q.push(root);while(!q.empty()){Node*cur=q.front();q.pop();if(cur->data==target)tar=cur;if(cur->left){par[cur->left]=cur;q.push(cur->left);}if(cur->right){par[cur->right]=cur;q.push(cur->right);}}returntar;}// Find nodes at distance k using BFSvector<int>kDistanceNodes(Node*root,inttarget,intk){vector<int>ans;// Build the parent mapping and find the target nodeNode*tar=markParents(root,target);unordered_set<Node*>vis;queue<Node*>q;q.push(tar);vis.insert(tar);intd=0;// Traverse level by levelwhile(!q.empty()&&d<k){intsz=q.size();while(sz--){Node*cur=q.front();q.pop();if(cur->left&&!vis.count(cur->left)){vis.insert(cur->left);q.push(cur->left);}if(cur->right&&!vis.count(cur->right)){vis.insert(cur->right);q.push(cur->right);}if(par.count(cur)&&!vis.count(par[cur])){vis.insert(par[cur]);q.push(par[cur]);}}d++;}while(!q.empty()){ans.push_back(q.front()->data);q.pop();}// Sort the resultsort(ans.begin(),ans.end());returnans;}intmain(){// Create the binary tree:// 1// / \ // 2 3// / \ // 4 5Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);inttarget=2;intk=2;vector<int>ans=kDistanceNodes(root,target,k);for(intx:ans)cout<<x<<" ";return0;}
Java
importjava.util.ArrayList;importjava.util.Queue;importjava.util.LinkedList;importjava.util.HashMap;importjava.util.HashSet;importjava.util.Collections;// Structure of Binary Tree NodeclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGFG{staticHashMap<Node,Node>par=newHashMap<>();// Build the parent mapping and locate the target nodestaticNodemarkParents(Noderoot,inttarget){Nodetar=null;Queue<Node>q=newLinkedList<>();q.add(root);while(!q.isEmpty()){Nodecur=q.poll();if(cur.data==target)tar=cur;if(cur.left!=null){par.put(cur.left,cur);q.add(cur.left);}if(cur.right!=null){par.put(cur.right,cur);q.add(cur.right);}}returntar;}// Find nodes at distance k using BFSstaticArrayList<Integer>kDistanceNodes(Noderoot,inttarget,intk){ArrayList<Integer>ans=newArrayList<>();// Build the parent mapping and find the target nodeNodetar=markParents(root,target);HashSet<Node>vis=newHashSet<>();Queue<Node>q=newLinkedList<>();q.add(tar);vis.add(tar);intd=0;// Traverse level by levelwhile(!q.isEmpty()&&d<k){intsz=q.size();while(sz-->0){Nodecur=q.poll();if(cur.left!=null&&!vis.contains(cur.left)){vis.add(cur.left);q.add(cur.left);}if(cur.right!=null&&!vis.contains(cur.right)){vis.add(cur.right);q.add(cur.right);}if(par.containsKey(cur)&&!vis.contains(par.get(cur))){vis.add(par.get(cur));q.add(par.get(cur));}}d++;}while(!q.isEmpty())ans.add(q.poll().data);// Sort the resultCollections.sort(ans);returnans;}publicstaticvoidmain(String[]args){// Create the binary tree:// 1// / \// 2 3// / \// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);inttarget=2;intk=2;ArrayList<Integer>ans=kDistanceNodes(root,target,k);for(intx:ans)System.out.print(x+" ");}}
Python
fromcollectionsimportdeque# Structure of Binary Tree NodeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Build the parent mapping and locate the target nodedefmarkParents(root,target,par):tar=Noneq=deque([root])whileq:cur=q.popleft()ifcur.data==target:tar=curifcur.left:par[cur.left]=curq.append(cur.left)ifcur.right:par[cur.right]=curq.append(cur.right)returntar# Find nodes at distance k using BFSdefkDistanceNodes(root,target,k):ans=[]ifrootisNone:returnanspar={}# Build the parent mapping and find the target nodetar=markParents(root,target,par)vis=set()q=deque([tar])vis.add(tar)d=0# Traverse level by levelwhileqandd<k:sz=len(q)whilesz>0:cur=q.popleft()ifcur.leftandcur.leftnotinvis:vis.add(cur.left)q.append(cur.left)ifcur.rightandcur.rightnotinvis:vis.add(cur.right)q.append(cur.right)ifcurinparandpar[cur]notinvis:vis.add(par[cur])q.append(par[cur])sz-=1d+=1whileq:ans.append(q.popleft().data)# Sort the resultans.sort()returnansif__name__=="__main__":# Create the binary tree:# 1# / \# 2 3# / \# 4 5root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)target=2k=2ans=kDistanceNodes(root,target,k)forxinans:print(x,end=" ")
C#
usingSystem;usingSystem.Collections.Generic;// Structure of Binary Tree NodeclassNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGFG{staticDictionary<Node,Node>par=newDictionary<Node,Node>();// Build the parent mapping and locate the target nodestaticNodemarkParents(Noderoot,inttarget){Nodetar=null;Queue<Node>q=newQueue<Node>();q.Enqueue(root);while(q.Count>0){Nodecur=q.Dequeue();if(cur.data==target)tar=cur;if(cur.left!=null){par[cur.left]=cur;q.Enqueue(cur.left);}if(cur.right!=null){par[cur.right]=cur;q.Enqueue(cur.right);}}returntar;}// Find nodes at distance k using BFSstaticList<int>kDistanceNodes(Noderoot,inttarget,intk){List<int>ans=newList<int>();// Build the parent mapping and find the target nodeNodetar=markParents(root,target);HashSet<Node>vis=newHashSet<Node>();Queue<Node>q=newQueue<Node>();q.Enqueue(tar);vis.Add(tar);intd=0;// Traverse level by levelwhile(q.Count>0&&d<k){intsz=q.Count;while(sz-->0){Nodecur=q.Dequeue();if(cur.left!=null&&!vis.Contains(cur.left)){vis.Add(cur.left);q.Enqueue(cur.left);}if(cur.right!=null&&!vis.Contains(cur.right)){vis.Add(cur.right);q.Enqueue(cur.right);}if(par.ContainsKey(cur)&&!vis.Contains(par[cur])){vis.Add(par[cur]);q.Enqueue(par[cur]);}}d++;}while(q.Count>0)ans.Add(q.Dequeue().data);// Sort the resultans.Sort();returnans;}publicstaticvoidMain(){// Create the binary tree:// 1// / \// 2 3// / \// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);inttarget=2;intk=2;List<int>ans=kDistanceNodes(root,target,k);foreach(intxinans)Console.Write(x+" ");}}
JavaScript
// Structure of Binary Tree NodeclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Build the parent mapping and locate the target nodefunctionmarkParents(root,target,par){lettar=null;letq=[root];letfront=0;while(front<q.length){letcur=q[front++];if(cur.data===target)tar=cur;if(cur.left){par.set(cur.left,cur);q.push(cur.left);}if(cur.right){par.set(cur.right,cur);q.push(cur.right);}}returntar;}// Find nodes at distance k using BFSfunctionkDistanceNodes(root,target,k){letans=[];// Build the parent mapping and find the target nodeletpar=newMap();lettar=markParents(root,target,par);letvis=newSet();letq=[tar];letfront=0;vis.add(tar);letd=0;// Traverse level by levelwhile(front<q.length&&d<k){letsz=q.length-front;while(sz--){letcur=q[front++];if(cur.left&&!vis.has(cur.left)){vis.add(cur.left);q.push(cur.left);}if(cur.right&&!vis.has(cur.right)){vis.add(cur.right);q.push(cur.right);}if(par.has(cur)&&!vis.has(par.get(cur))){vis.add(par.get(cur));q.push(par.get(cur));}}d++;}while(front<q.length)ans.push(q[front++].data);// Sort the resultans.sort((a,b)=>a-b);returnans;}// Driver code// Create the binary tree:// 1// / \// 2 3// / \// 4 5letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);lettarget=2;letk=2;letans=kDistanceNodes(root,target,k);for(letxofans)process.stdout.write(x+" ");