Nodes at given distance in binary tree | Practice | GeeksforGeeks

Given a binary tree, a target node in the binary tree, and an integer value k, find all the nodes that are at distance k from the given target node. No parent pointers are available.
Example 1:
Input:      
          20
        /    \
      8       22 
    /   \
   4    12 
       /   \
      10    14
Target Node = 8
K = 2
Output: 10 14 22
Explanation: The three nodes at distance 2
from node 8 are 10, 14, 22.


Example 2:
Input:      
         20
       /    \
      7      24
    /   \
   4     3
        /  
       1    
Target Node = 7
K = 2
Output: 1 24

Your Task:  
You don't need to read input or print anything. Complete the function KDistanceNodes() which takes the root of the tree, target, and K as input parameters and returns a list of nodes at k distance from target in a sorted order.

Expected Time Complexity: O(N*logN)
Expected Auxiliary Space: O(Height of tree)

Constraints:
1 ≤ N ≤ 103
1 ≤ data of node ≤ 104
1 ≤ target ≤ 104
1 ≤ k ≤ 20
0
ag9520061 day ago
What's wrong in my code? 
Why answer is coming in complete?
please help anyone
class Solution{private:int findDistance(Node *root, int x){   // Base case   if (root == NULL)     return -1;   // Initialize distance   int dist = -1;   // Check if x is present at root or in left   // subtree or right subtree.   if ((root->data == x) ||       (dist = findDistance(root->left, x)) >= 0 ||       (dist = findDistance(root->right, x)) >= 0)       return dist + 1;   return dist;}
void kDist(Node *head,Node *root,int target,int k, vector<int> &v){   if(root==NULL){       return;   }   if(abs(findDistance(head,root->data)-findDistance(head,target))==k){       v.push_back(root->data);   }   kDist(head,root->left,target,k,v);   kDist(head,root->right,target,k,v);}public:
   vector <int> KDistanceNodes(Node* root, int target , int k)   {       // return the sorted vector of all nodes at k dist       vector<int> v;       kDist(root,root,target,k,v);       sort(v.begin(),v.end());       return v;          }};
0
utkarshagarwal1012 days ago
class Solution
{
private:

public:
   
    bool find(Node* root, int target ,  vector<Node*>&paths){
        if(!root)
        {
            return false;
        }
        if(root->data == target){
            paths.push_back(root);
            return true;
        }
        if(find(root->left,target,paths)){
            paths.push_back(root);
            return true;
        }
        else if(find(root->right,target,paths)){
            paths.push_back(root);
            return true;
        }
        else{
            return false;
        }
        return false;
    }
    void klevelsDown(Node* root, int k,vector<int>&ans,Node* parent){
        if(!root||k<0|| root==parent)
            return;
        if(k==0){
            ans.push_back(root->data);
            return;
        }
     
        klevelsDown(root->left,k-1,ans,parent);
        klevelsDown(root->right,k-1,ans,parent);
    }
    vector <int> KDistanceNodes(Node* root, int target , int k)
    {
        // return the sorted vector of all nodes at k dist
        vector<Node*>paths;
        vector<int>ans;
        if(find(root,target,paths)==false)
            return ans;
        for(int i=0;i<paths.size();i++){
             klevelsDown(paths[i],k-i,ans,i==0 ? NULL :paths[i-1]);
        }
        sort(ans.begin(),ans.end());
        return ans;
    }
};
0
sounavapal1 week ago
0.23 sec solution:
class Solution{private:   vector<int> res;public:
   vector <int> KDistanceNodes(Node* root, int target , int k)   {       // return the sorted vector of all nodes at k dist       stack<Node*> s;       res.clear();       find(root,target,k,s);       sort(res.begin(),res.end());       auto it=unique(res.begin(), res.end());       res.resize(distance(res.begin(), it));       return res;   }   void find(Node* root,int target,int k,stack<Node*> s)   {       if(root==NULL)       return;       if(root->data==target)       {           check(root,k,s);           return;       }       s.push(root);       find(root->left,target,k,s);       find(root->right,target,k,s);   }   void check(Node* root,int k,stack<Node*> s)   {       if(k==0 && root!=NULL)       {           res.push_back(root->data);           return;       }       if(k==0)       return;       root->data=-1;       if(!s.empty())       {           Node* t=s.top();           s.pop();           if(t->data!=-1)           check(t,k-1,s);       }       if(root->left!=NULL && root->left->data!=-1)           check(root->left,k-1,s);       if(root->right!=NULL && root->right->data!=-1)           check(root->right,k-1,s);   }};
0
tapanmanu20002 weeks ago
Node* T = NULL;
    void preorder(Node* root, int target, map<Node*, Node*> &par){
        if(root == NULL) return;
        if(root->data == target) T = root;
        if(root->left){
            par[root->left] = root;
        }
        if(root->right){
            par[root->right] = root;
        }
        preorder(root->left, target, par);
        preorder(root->right, target, par);
    }
    vector <int> KDistanceNodes(Node* root, int target , int k)
    {
        // return the sorted vector of all nodes at k dist
        map<Node*,Node*> par;
        map<Node*, bool> visited;
        vector<int> sorted_neigh;
        int count = 0;
        preorder(root, target, par);
        par[root] = NULL;
        queue<Node*> q;
        q.push(T);
        while(!q.empty()){
            int size = q.size();
            while(size--){
                Node* t = q.front();
                q.pop();
                if(t->left && !visited[t->left]){
                    q.push(t->left);
                    visited[t->left] = true;
                }
                if(t->right && !visited[t->right]){
                    q.push(t->right);
                    visited[t->right] = true;
                }
                if(par[t] && !visited[par[t]]){
                    q.push(par[t]);
                    visited[par[t]] = true;
                }
            }
            count++;
            if(count == k){
                while(!q.empty()){
                    Node* t = q.front();
                    if(t != T)
                        sorted_neigh.push_back(t->data);
                    q.pop();
                }
                break;
            }
        }
        sort(sorted_neigh.begin(),sorted_neigh.end());
        return sorted_neigh;
    }
0
rohit250820003 weeks ago
class Solution{public:   unordered_map<Node *, Node *> hashMap;     unordered_set<Node * > visited;     Node * targetNode;       void inorder(Node * root, int target) {       if(root) {           if(root->left) hashMap.insert({root->left, root});             if(root->right) hashMap.insert({root->right, root});            if(root->data == target) {               targetNode = root;            }           inorder(root->left, target);            inorder(root->right, target);         }   }      vector<int> KDistanceNodes(Node* root, int target, int k) {       inorder(root, target);        queue<Node*> q;         q.push(targetNode);         int level = 0;       while(!q.empty() && level != k) {             int size = q.size();             for(int i = 0; i < size; ++i) {              Node * curr = q.front();                q.pop();                 if(visited.find(curr) == visited.end()) {                   visited.insert(curr);                     if(curr->left && visited.find(curr->left) == visited.end()) {                       q.push(curr->left);                    }                   if(curr->right && visited.find(curr->right) == visited.end()) {                       q.push(curr->right);                    }                   if(hashMap.find(curr) != hashMap.end() && visited.find(hashMap[curr]) == visited.end()) {                       q.push(hashMap[curr]);                         }               }           }           level++;        }       vector<int> result;         while(!q.empty()) {           result.push_back(q.front()->data);            q.pop();        }       sort(result.begin(), result.end());        return result;    } }; 
0
akashmr10961 month ago
class Solution
{
    static Node contended = null;
    public static ArrayList<Integer> KDistanceNodes(Node root, int target , int k)
    {
        contended = null;
        Map<Node, ArrayList<Node>> graph = new HashMap<>();
        createGraph(root, null, target, graph);
        
        ArrayList<Integer> result = new ArrayList<>();
        dfs(contended, null, graph, k, result);
        Collections.sort(result);
        return result;
    }
    
    private static void createGraph(Node root, Node parent, int target, Map<Node, ArrayList<Node>> graph) {
        
        if (root == null) {
            return;
        }
        
        if (root.data == target) {
            contended = root;
        }
        
        graph.putIfAbsent(root, new ArrayList<>());
        ArrayList<Node> adj = graph.get(root);
        
        if (root.left != null) {
            adj.add(root.left);
        }
        
        if (root.right != null) {
            adj.add(root.right);
        }
        
        if (parent != null) {
            adj.add(parent);
        }
        
        createGraph(root.left, root, target, graph);
        createGraph(root.right, root, target, graph);
    }

    private static void dfs(Node v, Node parent, Map<Node, ArrayList<Node>> graph, int k, ArrayList<Integer> result) {
        
        if (k == 0) {
            result.add(v.data);
            return;
        }
        
        for(Node n: graph.get(v)) {
            if (!n.equals(parent)) {
                dfs(n, v, graph, k-1, result);
            }
        }
    }
    
}
0
samanyupobbati2 months ago
Simple C++ solution using recursion.
    vector<int> ans;      void down_rec(Node* root, int k){              if(root == NULL)           return;              if(k == 0){           ans.push_back(root->data);       }              down_rec(root->left, k-1);       down_rec(root->right, k-1);                 }      int up_rec(Node *root, int target, int k){              if(root == NULL)           return -1;              if(root->data == target){           down_rec(root, k);           return k-1;       }              int lr = up_rec(root->left, target, k);       int rr = up_rec(root->right, target, k);              if(lr == 0 || rr == 0){           ans.push_back(root->data);           return -1;       }              if(lr != -1){           down_rec(root->right, lr - 1);           return lr - 1;       }       else if(rr != -1){           down_rec(root->left, rr - 1);           return rr - 1;       }              return -1;          }
0
hamidnourashraf2 months ago
Total Time Taken:
0.3/1.6
 
class Solution:
    def find_node(self, root, target, path):
        if root is None:
            return False
        path.append(root)
        if root.data == target:
            return True
        if self.find_node(root.left, target, path) or self.find_node(root.right, target, path):
            return True
        path.pop()
        return False
    def find_distance_node(self, node, dist, res):
        if node is None:
            return
        if dist < 0:
            return
        if dist == 0:
            res.append(node.data)
            return
        self.find_distance_node(node.left, dist-1, res)
        self.find_distance_node(node.right, dist-1, res)
        
    def KDistanceNodes(self,root,target,k):
        path = []
        self.find_node(root, target, path)
        res = []
        if len(path) == 1:
            self.find_distance_node(path[0], k, res)
        else:
            self.find_distance_node(path[-1], k, res)
            
            curr = path.pop()
            k = k -1
            while k > 0 and len(path) > 0:
                if path[-1].right == curr:
                    self.find_distance_node(path[-1].left, k-1, res)
                elif path[-1].left == curr:
                    self.find_distance_node(path[-1].right, k-1, res)
                curr = path.pop()
                k = k - 1
            if len(path) > 0:
                res.append(path[-1].data)
 
                
        return sorted(res)
+1
haritasboy12053 months ago
C++ Solution
 
void mark_parent(Node* root, unordered_map<Node*,Node*> &parent_track, int target,Node* &tgt)
    {
        queue<Node*> q;
        q.push(root);
        while(!q.empty())
        {
            Node*curr = q.front();
            q.pop();
            if(curr->data == target)
                tgt = curr;
            if(curr->left != NULL)
            {
                parent_track[curr->left] = curr;
                q.push(curr->left);
            }
            if(curr->right != NULL)
            {
                parent_track[curr->right] = curr;
                q.push(curr->right);
            }
        }
    }

    vector <int> KDistanceNodes(Node* root, int target , int k)
    {
        // return the sorted vector of all nodes at k dist
        unordered_map<Node*,Node*> parent_track;
        Node* tgt = NULL;
        mark_parent(root,parent_track,target,tgt);  //After this function we'll get our parent
        
        unordered_map<Node*,bool> visited;
        queue<Node*> q;
        q.push(tgt);
        visited[tgt] = true;
        int curr_level = 0;
        while(!q.empty())
        {
            int size = q.size();
            if(curr_level++ == k)
                break;
            //curr_level++;
            for(int i=0;i<size;i++)
            {
                Node* temp = q.front();
                q.pop();
                if(temp->left && !visited[temp->left])
                {
                    q.push(temp->left);
                    visited[temp->left] = true;
                }
                if(temp->right && !visited[temp->right])
                {
                    q.push(temp->right);
                    visited[temp->right] = true;
                }
                if(parent_track[temp] && !visited[parent_track[temp]])
                {
                    q.push(parent_track[temp]);
                    visited[parent_track[temp]] = true;
                }
            }
        }
        
        vector<int> result;
        while(!q.empty())
        {
            Node* curr = q.front();
            q.pop();
            result.push_back(curr->data);
        }
        sort(result.begin(),result.end());
        return result;
        
    }
0
abhiiishek073 months ago
C++ SOLUTION WITH EXPLANATION:-
find the root to node path.It will help in getting the resultant nodes.
store this path in stack.
Now we have to print the nodes at k distance for every node in the path 
for the target node we have to print all nodes at distance k.
for father of target we have to print all nodes at distance k-1 and remember we can't print nodes of target. so we have a blocker variable.
   void printKlevelDown(Node* root,Node* blocker, vector<int> &res, int x)
   {
       if(!root || x<0 || root==blocker)
       return;
       
       if(x==0)
       res.push_back(root->data);
       
       printKlevelDown(root->left,blocker,res,x-1);
       printKlevelDown(root->right,blocker,res,x-1);
   }
   void rootToNodePath(Node* root, int target, vector<Node*>&v, stack<Node*> &st)
   {
       if(!root)
       return;
       
       v.push_back(root);
       
       if(root->data==target)
       {
           for(int i=0;i<v.size();i++)
           st.push(v[i]);
           return;
       }
       
       rootToNodePath(root->left,target,v,st);
       rootToNodePath(root->right,target,v,st);
       
       v.pop_back();
   }
   vector <int> KDistanceNodes(Node* root, int target , int k)
   {
       // return the sorted vector of all nodes at k dist
       vector<int> res;
       vector<Node*>v;
       stack<Node*>st;
       rootToNodePath(root,target,v,st);
       
       Node* blocker=NULL;
       int d=0;
       while(!st.empty() && d<=k)
       {
           printKlevelDown(st.top(),blocker,res,k-d);
           d++;
           blocker=st.top();
           st.pop();
       }
       sort(res.begin(),res.end());
       return res;
   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.