Node at distance | Practice | GeeksforGeeks

Given a Binary Tree and a positive integer k. The task is to count all distinct nodes that are distance k from a leaf node. A node is at k distance from a leaf if it is present k levels above the leaf and also, is a direct ancestor of this leaf node. If k is more than the height of Binary Tree, then nothing should be counted.
Example 1:
Input:
        1
      /   \
     2     3
   /  \   /  \
  4   5  6    7
          \ 
          8
K = 2
Output: 2
Explanation: There are only two unique
nodes that are at a distance of 2 units
from the leaf node. (node 3 for leaf
with value 8 and node 1 for leaves with
values 4, 5 and 7)
Note that node 2
isn't considered for leaf with value
8 because it isn't a direct ancestor
of node 8.

Example 2:
Input:
          1
         /
        3
       /
      5
    /  \
   7    8
         \
          9
K = 4
Output: 1
Explanation: Only one node is there
which is at a distance of 4 units
from the leaf node.(node 1 for leaf
with value 9) 
Your Task:
You don't have to read input or print anything. Complete the function printKDistantfromLeaf() that takes root node and k as inputs and returns the number of nodes that are at distance k from a leaf node. Any such node should be counted only once. For example, if a node is at a distance k from 2 or more leaf nodes, then it would add only 1 to our count.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the Tree).
Constraints:
1 <= N <= 105
Note: The Input/Output format and Example are 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.
+1
kalamarham4 days ago
bool solve(Node* root,int k){   if(root==NULL) return false;   if(k==0 and root->left==NULL and root->right==NULL) return true;   return solve(root->left,k-1) or solve(root->right,k-1);}void ok(Node* root,int k,int &c){   if(root==NULL) return;   ok(root->left,k,c);   if(solve(root,k))   {       c++;   }   ok(root->right,k,c);}int printKDistantfromLeaf(Node* root, int k){//Add your code here.int c=0;ok(root,k,c);return c;}
0
aryanm4682 weeks ago
unordered_set<int> u;
int pd(Node* root,int k,int d,int &c){   if(root==NULL)       return 0;            u.insert(d);           if(d>=k && root->left==NULL && root->right==NULL)            {                if(u.find(d-k)!=u.end())                {                    c++;                    auto i=u.find(d-k);                    u.erase(i);                }            }                        pd(root->left,k,d+1,c);            pd(root->right,k,d+1,c);}
int printKDistantfromLeaf(Node* root, int k){int c=0;pd(root,k,0,c);return c;}
+1
shirurrohit1 month ago
PYTHON - No hashmap / Set
 
def helper(root, k):
    global count
    
    if root == None:
        return False
    
    if root.left == None and root.right == None and k == 0:
        return True
    
    return helper(root.left, k-1) or helper(root.right, k-1)

def inorder(root, k):
    global count
    
    if root == None:
        return
    
    inorder(root.left, k)
    
    if helper(root, k):
        count += 1
        
    inorder(root.right, k)

def printKDistantfromLeaf(root, k):
    global count
    count = 0
    inorder(root, k)
    return count
0
alamfarhan3892 months ago
bool check(Node *root, int k) {   if(root == NULL) return false;   if(k == 0 && root->left == NULL && root->right == NULL) return true;      return check(root->left, k-1) || check(root->right, k-1);}
int solve(Node *root, int k) {   if(root == NULL) return 0;      int ans = check(root, k) + solve(root->left, k) + solve(root->right, k);      return ans;}int printKDistantfromLeaf(Node* root, int k) {   return solve(root, k);}
+1
jai20222 months ago
EASY C++ SOLUTION WITH STEPS:
/*Idea: First traverse through the tree with any traversal technique and then while traversal,check for every node if its distance from leaf node is k or not.We simply move downwards from the root and decrease k for every level. if k becomes 0 at leaf nodewe simply add it in a data structure like set(or any) and return the size of it.As only those elements which are at k distance from leaf are stored in set,so size of set will return the total number of elements.*/
 
 
bool check(Node *root,int k){   if(root==NULL) return false;   if(root->right==NULL && root->left==NULL){       if(k==0) return true;       else return false;   }      bool left = check(root->left,k-1);   bool right = check(root->right,k-1);      return left||right;}
 
void inorder(Node *root,int k,unordered_set<Node*> &s){   if(root==NULL) return;   inorder(root->left,k,s);   if(check(root,k)){       s.insert(root);   }   inorder(root->right,k,s);}
 
int printKDistantfromLeaf(Node* root, int k){unordered_set<Node*> s;inorder(root,k,s);return s.size();}
+2
harendraseervi1234567892 months ago
void serAndPush(Node*root,vector<Node*>v,int k,set<Node*>&s){
   if(root==NULL) return;
   v.push_back(root);
   serAndPush(root->left,v,k,s);
   serAndPush(root->right,v,k,s);
   if(root->left==NULL && root->right==NULL){
       if(k>=v.size()) return;
       int t=0;
       for(int i=v.size()-1;i>=0;i--){
           if(t==k){
               s.insert(v[i]);
               return;
           }
           t++;
       }
   }
}
int printKDistantfromLeaf(Node* root, int k)
{
set<Node*>s;
vector<Node*>v;
serAndPush(root,v,k,s);
return s.size();

}
+1
aloksinghbais023 months ago
C++ solution having time complexity as O(N) and space complexity as O(N) is as follows :-
 
Execution Time :- 0.2 / 1.1 sec
 
void preorder(Node *node,Node *p,unordered_map<Node*,Node*> &par,vector<Node*> &leaf){   if(!node) return;   par[node] = p;   preorder(node->left,node,par,leaf);   preorder(node->right,node,par,leaf);   if(!node->left && !node->right) leaf.push_back(node);}
int printKDistantfromLeaf(Node* root, int k){vector<Node*> leaf;unordered_map<Node*,Node*> par;preorder(root,nullptr,par,leaf);queue<pair<Node*,int>> q;for(Node *node: leaf) q.push({node,0});unordered_map<Node*,bool> taken;int cnt = 0;while(!q.empty()){    auto p = q.front();    q.pop();    Node *node = p.first;    int dis = p.second;        if(dis == k && !taken[node]){        cnt++;        taken[node] = true;    }        if(par[node]){        q.push({par[node],dis+1});    }}return (cnt);}
+1
abhixhek053 months ago
//Using inorder traversal

unordered_set<Node*> s;
    bool func(Node* root,int k)
    {
        if(root==NULL){
            return false;
        }
        if(root->left==NULL && root->right==NULL){
            if(k==0){
                return true;
            }
            return false;
        }
        bool left=func(root->left,k-1);
        bool right=func(root->right,k-1);
        return left||right;
    }
    void inorder(Node* root,int k){
        if(root==NULL){
            return;
        }
        inorder(root->left,k);
        if(func(root,k)){
            s.insert(root);
        }
        inorder(root->right,k);
    }
    int printKDistantfromLeaf(Node* root, int k)
    {
       s.clear();
        inorder(root,k);
        return s.size();
    }
0
shiva1090
This comment was deleted.
+1
shyamprakash8073 months ago
Simple Python Solution:
Time Taken : 0.3/1.4
 
from collections import dequedef printKDistantfromLeaf(root, k):   q = deque()   p = dict()   q.append(root)   leaf = []   while len(q)>0:       curr = q.popleft()       if curr.left != None:           q.append(curr.left)           p[curr.left] = curr       if curr.right != None:           q.append(curr.right)           p[curr.right] = curr       if curr.left == curr.right == None:           leaf.append(curr)   ans = set()   for node in leaf:       x = Present(node, p, k)       if x != None:           ans.add(x)   return len(ans)   def Present(node, p, k):   if k == 0:       return node   if node in p:       return Present(p[node], p, k-1)   return None
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.