• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to secondary sidebar

GoHired

Interview Questions asked in Google, Microsoft, Amazon

Join WeekEnd Online Batch from 4-April-2020 on How to Crack Coding Interview in Just 10 Weeks : Fees just 20,000 INR

  • Home
  • Best Java Books
  • Algorithm
  • Internship
  • Certificates
  • About Us
  • Contact Us
  • Privacy Policy
  • Array
  • Stack
  • Queue
  • LinkedList
  • DP
  • Strings
  • Tree
  • Mathametical
  • Puzzles
  • Graph

Print all nodes that are at distance k from a leaf node

October 9, 2014 by Dhaval Dave

Given a Binary Tree and a positive integer k, print all nodes that are distance k from a leaf node.

Here the meaning of distance k from a leaf means k levels higher than a leaf node.
For example if k is more than height of Binary Tree, then nothing should be printed. Expected time complexity is O(n) where n is the number nodes in the given Binary Tree. 

           [1]
          /   \
       [2]     [3]
      /  \     /  \
    [4]  [5] [6]  [7]
    /
  [8]

Here Output should be 1, and 2 for K=2 as both are at 2 distance from leaf nodes.
1 is at K=2 distance from 5 and  2 is K=2 distance from 8.

Method 1)

We are setting some arbitrary large number as height.
with each associated node, will keep this height and decrements it.

eg.
Height[1000]=1
Height [999]=2
Height [998]=4
Height [997]=8
Height [998]=5
Height [999]=3
Height [998]=6
Height [998]=7

When we encounter a node which is leaf (ie. No left no right Sub tree)
we print Height [length+k];

say here

For Node 8K distance node is= 2
For Node 5K distance node is= 1
For Node 6K distance node is= 1

Now think for algorithm on ur own :
else see working code at http://ideone.com/htifVi

Code :

#include <iostream>
using namespace std;
#define MAX_HEIGHT 1000

struct Node
{
    int key;
    Node *left, *right;
};

Node* newNode(int key)
{
    Node* node = new Node;
    node->key = key;
    node->left = node->right = NULL;
    return (node);
}

void kDistantFromLeafUtil(Node* node, int height[], int pathLen, int k)
{
    if (node==NULL) return;

    height[pathLen] =  node->key;
    pathLen--;

    if(node->left == NULL && node->right == NULL){
       cout <<"For Node "<<node->key <<"K distance node is= "<< height[pathLen+k+1] << " "<<endl;
       return;
    }
    kDistantFromLeafUtil(node->left, height,  pathLen, k);
    kDistantFromLeafUtil(node->right, height,  pathLen, k);
}

void printKDistantfromLeaf(Node* node, int k)
{
    int height[MAX_HEIGHT];
    bool visited[MAX_HEIGHT] = {false};
    kDistantFromLeafUtil(node, height, 1000, k);
}

int main()
{
    Node * root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    root->right->left = newNode(6);
    root->right->right = newNode(7);
    root->left->left->right = newNode(8);
    printKDistantfromLeaf(root, 2);

    return 0;
}

 

Method 2) Instead decrementing  pathLen we can think for approch where we can increment pathLen in order to decrease memory usage.

Changes required

void kDistantFromLeafUtil(Node* node, int height[], int pathLen, int k)
{
    if (node==NULL) return;

    height[pathLen] =  node->key;
    pathLen++;
//SEE CHANGES

if(node->left == NULL && node->right == NULL){
    cout <<“For Node “<<node->key <<“K distance node is= “<< height[pathLen-k-1] << ” “<<endl;
// SEE CHANGES
    return;
}
    kDistantFromLeafUtil(node->left, height,  pathLen, k);
    kDistantFromLeafUtil(node->right, height,  pathLen, k);
}

IN  void printKDistantfromLeaf(Node* node, int k){}
kDistantFromLeafUtil(node, height, 0, k);

clash of clans hack no survey

Similar Articles

Filed Under: Amazon Interview Question, Flipkart Interview Questions, Interview Questions, Microsoft Interview Questions, problem Tagged With: Binary Tree, tree

Reader Interactions

Primary Sidebar

Join WeekEnd Online/Offline Batch from 4-April-2020 on How to Crack Coding Interview in Just 10 Weeks : Fees just 20,000 INR

Join WeekEnd Online/Offline Batch from 4-April-2020

WhatsApp us

Secondary Sidebar

Custom Search

  • How I cracked AMAZON
  • LeetCode
  • Adobe
  • Amazon
  • Facebook
  • Microsoft
  • Hacker Earth
  • CSE Interview

Top Rated Questions

In Given LinkedList Divide LL in N Sub parts and delete first K nodes of each part

1014 Practice Question of New GRE – Princeton

Handle duplicates in Binary Search Tree

SAP Off Campus Hiring_ March 2015 Computer Skills

Count Possible Decodings of a given Digit Sequence

Stickler thief

LeetCode: Container With Most Water

Calculate price of parking from parking start end time prices

There are N nuts and N bolts, u have to find all the pairs of nuts and bolts in minimum no. of iteration

TicTacToe Game As Asked in Flipkart

Convert number to words java

Find Percentage of Words matching in Two Strings

Top 10 Interviews Techniqes for Campus Interview in IIT NIT BITS for MTech

Given array of 0’s and 1’s. All 0’s are coming first followed by 1’s. find the position of first 1

Word Break Problem

write a c program that given a set a of n numbers and another number x determines whether or not there exist two elements in s whose sum is exactly x

Circular Linked List

Code Chef PRGIFT Solution

Search element in a matrix with all rows and columns in sorted order

Possible sizes of bus to carry n groups of friends

CodeChef Code SGARDEN

Given a string, find the first character which is non-repetitive

Common Ancestor in a Binary Tree or Binary Search Tree

How Radix sort works

Generate largest number arranging a no. of given non negative integer numbers

Practo Hiring Experience

Right view of Binary tree

K’th Largest Element in BST when modification to BST is not allowed

BFS (Breath First Search)

N teams are participating. each team plays twice with all other teams. Some of them will go to the semi final. Find Minimum and Maximum number of matches that a team has to win to qualify for finals ?

Copyright © 2025 · Genesis Framework · WordPress · Log in