K distance from root | Practice | GeeksforGeeks

Given a Binary Tree of size N and an integer K. Print all nodes that are at distance k from root (root is considered at distance 0 from itself). Nodes should be printed from left to right. If k is more that height of tree, nothing should be printed.
For example, if below is given tree and k is 2. Output should be 4 5 6.
          1
       /     \
     2        3
   /         /   \
  4        5    6 
     \
      8
Example 1:
Input:
K = 0
      1
    /   \
   3     2
Output: 1


Example 2:
Input:
K = 3
        3
       /
      2
       \
        1
      /  \
     5    3
Output: 5 3
Your Task:
You don't have to take input. Complete the function Kdistance() that accepts root node and k as parameter and return the value of the nodes that are at a distance k from the root. (The values are returned as vector in cpp, as ArrayList in java and list in python)
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the Tree).
Constraints:
1 <= N <= 104
0 <= K <= 30

Note: The Input/Ouput format and Example is given are used for the system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from the stdin/console. The task is to complete the function specified, and not to write the full code.
0
ravi1010prakash1 day ago
vector<int>v;vector<int> Kdistance(struct Node *root, int k){ // vector<int>v; if(root==NULL) return v; if(k==0) v.push_back(root->data); else{  Kdistance(root->left,k-1);   Kdistance(root->right,k-1);}   return v;}
what is error in this code in given ???
 
0
ravi1010prakash
This comment was deleted.
0
shivanshmahajan8762 days ago
void k_d(Node * root , int k ,int level , vector <int> &ans){   if(root == NULL)   {       return ;   }   if(level == k)   {       ans.push_back(root->data);   }   k_d(root->left , k , level+1 , ans);   k_d(root->right , k , level+1 , ans);   }vector<int> Kdistance(struct Node *root, int k){    vector <int> ans;   k_d(root , k , 0 , ans);   return ans;}
 
0
mohittpattel2 weeks ago
Easy C++ Sol with explanation.
//Function to find the kth node
void kNode(Node* root, int k, vector<int>& result)
{
    //Base condition
    if(root == nullptr || k < 0)
        return;
    if(k == 0)
        result.push_back(root->data);
    //call the recurrsive function for the left subtree and decerment the value k by one
    kNode(root->left, k-1, result);
    //similarly with right node ofthe tree
    kNode(root->right, k-1, result);
}

// function should print the nodes at k distance from root
vector<int> Kdistance(struct Node *root, int k)
{
  // Your code here
  vector<int> result;
  //call the recurrsive function to find all itr nodes utp kth distance
  kNode(root, k, result);
  
  return result;
}
+1
alreadytaken2 weeks ago
void height(struct Node* root, int k, vector<int> &ans,int level){   if (root==NULL) return;   if (level == k) ans.push_back(root->data);   height(root->left,k,ans,level+1);   height(root->right,k,ans,level+1);}vector<int> Kdistance(struct Node *root, int k){ // Your code here vector<int> ans; height(root,k,ans,0); return ans; }
0
shubhamtripathy2 weeks ago
Easy Python Solution
def Kutil(root,k,level,result):
    if root is None:
        return
    if level==k:
        result.append(root.data)
    Kutil(root.left,k,level+1,result)
    Kutil(root.right,k,level+1,result)
    
def KDistance(root,k):
 
    result =[]
    Kutil(root,k,0,result)
    # code here
    return result 
0
roopsaisurampudi1 month ago
Java Iterative Solution (BFS)
ArrayList<Integer> Kdistance(Node root, int k)
     {
          // Your code here
          ArrayList<Integer> ans = new ArrayList<>();
          Queue<Node> q = new LinkedList<>();
          q.add(root);
          int K = -1;
          while(!q.isEmpty()) {
              int len = q.size();
              K++;
              for(int i = 0; i < len; i++) {
                  if (K == k) {
                      Node curr = q.poll();
                      ans.add(curr.data);
                      if (curr.left != null) q.add(curr.left);
                      if (curr.right != null) q.add(curr.right);
                  } else {
                      Node curr = q.poll();
                      
                      if (curr.left != null) q.add(curr.left);
                      if (curr.right != null) q.add(curr.right);
                  }
                  
              }
              if (K == k) break;
              
          }
          return ans;
     }
0
rohanyt741 month ago
void K(Node*root,vector<int>&res,int k,int level){   if(root==NULL)return;   if(level==k)res.push_back(root->data);   K(root->left,res,k,level+1);   K(root->right,res,k,level+1);}vector<int> Kdistance(struct Node *root, int k){ // Your code here vector<int>res; K(root,res,k,0); return res;}
0
rajsinh21811 month ago
Easy CPP BFS approach:
vector<int> Kdistance(struct Node *root, int k)
{
    vector <int> v;
    if(root==NULL) return v;
    queue <Node*> q;
    q.push(root);
    while(!q.empty()){
        for(int i=0;i<q.size();i++){
            Node* temp = q.front();
            if(k==0)v.push_back(temp->data); //only change
            q.pop();
            if(temp->left!=NULL)q.push(temp->left);
            if(temp->right!=NULL)q.push(temp->right);
        }
        k--;//updation
    }
    return v;
}
0
ashutos17sharma89891 month ago
class Tree
{
     // Recursive function to print right view of a binary tree.
     
     ArrayList<Integer> Kdistance(Node root, int k)
     {
          // Your code here
          ArrayList<Integer> ans = new ArrayList<>();
          if(root==null){
              return ans;
          }
          if(k==0){
             ans.add(root.data);
          }
         ans.addAll(Kdistance(root.left,  k-1));
        ans.addAll(Kdistance(root.right,  k-1));
         return ans; 
     }
}

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.