For a Given node of a binary tree, print the K distance nodes.

Problem You are given a function printKDistanceNodes which takes in a root node of a binary tree, a start node and an integer K. Complete the function to print the value of all the nodes (one-per-line) which are a K distance from the given start node in sorted order. Distance can be upwards or downwards. Example start node = 18, k = 2 , then output = 2, 19, 25 [Read More]

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

Problem 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 is different from previous post. Here k distance 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. [Read More]

Print nodes at k distance from root

Given a root of a tree, and an integer k. Print all the nodes which are at k distance from root. For example, in the below tree, 4, 5 & 8 are at distance 2 from root. 1 / \\ 2 3 / \\ / 4 5 8 Code: void printKDistant(node \*root , int k) { if(root == NULL) return; if( k == 0 ) { printf( "%d ", root->data ); return ; } else { printKDistant( root->left, k-1 ) ; printKDistant( root->right, k-1 ) ; } } Time Complexity: O(n) where n is number of nodes in the given binary tree. [Read More]