Print nodes at k distance from root
Last Updated :
17 Oct, 2023
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
The problem can be solved using recursion. Thanks to eldho for suggesting the solution.
Implementation:
C++
#include<bits/stdc++.h>
using namespace std;
class node
{
public :
int data;
node* left;
node* right;
node( int data)
{
this ->data = data;
this ->left = NULL;
this ->right = NULL;
}
};
void printKDistant(node *root , int k)
{
if (root == NULL|| k < 0 )
return ;
if ( k == 0 )
{
cout << root->data << " " ;
return ;
}
printKDistant( root->left, k - 1 ) ;
printKDistant( root->right, k - 1 ) ;
}
int main()
{
node *root = new node(1);
root->left = new node(2);
root->right = new node(3);
root->left->left = new node(4);
root->left->right = new node(5);
root->right->left = new node(8);
printKDistant(root, 2);
return 0;
}
|
C
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node* left;
struct node* right;
};
void printKDistant( struct node *root , int k)
{
if (root == NULL|| k < 0 )
return ;
if ( k == 0 )
{
printf ( "%d " , root->data );
return ;
}
printKDistant( root->left, k-1 ) ;
printKDistant( root->right, k-1 ) ;
}
struct node* newNode( int data)
{
struct node* node = ( struct node*)
malloc ( sizeof ( struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
int main()
{
struct 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(8);
printKDistant(root, 2);
getchar ();
return 0;
}
|
Java
class Node
{
int data;
Node left, right;
Node( int item)
{
data = item;
left = right = null ;
}
}
class BinaryTree
{
Node root;
void printKDistant(Node node, int k)
{
if (node == null || k < 0 )
return ;
if (k == 0 )
{
System.out.print(node.data + " " );
return ;
}
printKDistant(node.left, k - 1 );
printKDistant(node.right, k - 1 );
}
public static void main(String args[]) {
BinaryTree tree = new BinaryTree();
tree.root = new Node( 1 );
tree.root.left = new Node( 2 );
tree.root.right = new Node( 3 );
tree.root.left.left = new Node( 4 );
tree.root.left.right = new Node( 5 );
tree.root.right.left = new Node( 8 );
tree.printKDistant(tree.root, 2 );
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def printKDistant(root, k):
if root is None :
return
if k = = 0 :
print (root.data,end = ' ' )
else :
printKDistant(root.left, k - 1 )
printKDistant(root.right, k - 1 )
root = Node( 1 )
root.left = Node( 2 )
root.right = Node( 3 )
root.left.left = Node( 4 )
root.left.right = Node( 5 )
root.right.left = Node( 8 )
printKDistant(root, 2 )
|
C#
using System;
public class Node
{
public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = right = null ;
}
}
public class BinaryTree
{
public Node root;
public virtual void printKDistant(Node node, int k)
{
if (node == null || k < 0 )
{
return ;
}
if (k == 0)
{
Console.Write(node.data + " " );
return ;
}
printKDistant(node.left, k - 1);
printKDistant(node.right, k - 1);
}
public static void Main( string [] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(8);
tree.printKDistant(tree.root, 2);
}
}
|
Javascript
<script>
class Node
{
constructor(item)
{
this .data = item;
this .left = null ;
this .right = null ;
}
}
var root = null ;
function printKDistant(node, k)
{
if (node == null || k < 0 )
{
return ;
}
if (k == 0)
{
document.write(node.data + " " );
return ;
}
printKDistant(node.left, k - 1);
printKDistant(node.right, k - 1);
}
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(8);
printKDistant(root, 2);
</script>
|
Time Complexity: O(n) where n is number of nodes in the given binary tree.
Space Complexity : O(height of the binary tree).
Note-
- If it’s true print the node – Always check the K distance == 0 at every node
- the left or right subtree – Decrement the distance by 1 when you are passing to its subtree
Another Approach– We can do a level order traversal and keep track of the level.when current level is equal to k, then print all the nodes of that level.
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *left, *right;
};
void printKDistant(Node* root, int k)
{
if (root == NULL)
return ;
queue<Node*> q;
q.push(root);
int lvl = 0;
while (!q.empty()) {
int n = q.size();
if (lvl == k) {
for ( int i = 0; i < n; i++) {
cout << q.front()->data << " " ;
q.pop();
}
return ;
}
for ( int i = 0; i < n; i++) {
Node* temp = q.front();
q.pop();
if (temp->left != NULL)
q.push(temp->left);
if (temp->right != NULL)
q.push(temp->right);
}
lvl += 1;
}
}
Node* newNode( int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
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(8);
printKDistant(root, 2);
return 0;
}
|
Java
import java.util.LinkedList;
import java.util.Queue;
class Node {
int data;
Node left, right;
public Node( int item)
{
data = item;
left = null ;
right = null ;
}
}
class BinaryTree {
Node root;
void printKDistant(Node node, int k)
{
Queue<Node> queue = new LinkedList<Node>();
queue.add(root);
int lvl = 0 ;
while (!queue.isEmpty()) {
int n = queue.size();
if (lvl == k) {
for ( int i = 0 ; i < n; i++) {
Node tempNode = queue.poll();
System.out.print(tempNode.data + " " );
}
return ;
}
for ( int i = 0 ; i < n; i++) {
Node tempNode = queue.poll();
if (tempNode.left != null )
queue.add(tempNode.left);
if (tempNode.right != null )
queue.add(tempNode.right);
}
lvl++;
}
}
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node( 1 );
tree.root.left = new Node( 2 );
tree.root.right = new Node( 3 );
tree.root.left.left = new Node( 4 );
tree.root.left.right = new Node( 5 );
tree.root.right.left = new Node( 8 );
tree.printKDistant(tree.root, 2 );
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def printKDistant(root, k):
if root is None :
return
q = []
q.append(root)
lvl = 0
while (q):
n = len (q)
if lvl = = k:
for i in range (n):
print ((q[i].data), end = " " )
return
for i in range ( 1 , n + 1 ):
temp = q.pop( 0 )
if temp.left:
q.append(temp.left)
if temp.right:
q.append(temp.right)
lvl + = 1
if lvl < k:
return
root = Node( 1 )
root.left = Node( 2 )
root.right = Node( 3 )
root.left.left = Node( 4 )
root.left.right = Node( 5 )
root.right.left = Node( 8 )
printKDistant(root, 2 )
|
C#
using System;
using System.Collections.Generic;
public class Node {
public int data;
public Node left, right;
public Node( int data)
{
this .data = data;
left = null ;
right = null ;
}
}
public class GFG {
public Node root;
public void printKDistant(Node node, int k)
{
Queue<Node> queue = new Queue<Node>();
queue.Enqueue(node);
int lvl = 0;
while (queue.Count != 0) {
int n = queue.Count;
if (lvl == k) {
for ( int i = 0; i < n; i++) {
Node tempNode = queue.Dequeue();
Console.Write(tempNode.data + " " );
}
return ;
}
for ( int i = 0; i < n; i++) {
Node tempNode = queue.Dequeue();
if (tempNode.left != null )
queue.Enqueue(tempNode.left);
if (tempNode.right != null )
queue.Enqueue(tempNode.right);
}
lvl++;
}
}
public static void Main()
{
GFG tree = new GFG();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(8);
tree.printKDistant(tree.root, 2);
}
}
|
Javascript
class Node {
constructor(val) {
this .data = val;
this .left = null ;
this .right = null ;
}
}
function printKDistant(root, k)
{
if (root == null ) return ;
var queue = [];
queue.push(root);
var lvl = 0;
while (queue.length != 0) {
var n = queue.length;
if (lvl == k){
for ( var i = 0; i<n; i++){
var tempNode = queue.shift();
console.log(tempNode.data + " " );
}
return ;
}
for ( var i=0; i<n; i++){
var tempNode = queue.shift();
if (tempNode.left != null ) queue.push(tempNode.left);
if (tempNode.right != null ) queue.push(tempNode.right);
}
lvl++;
}
}
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(8);
printKDistant(root, 2);
|
Time Complexity: O(n) where n is number of nodes in the given binary tree.
Space Complexity: O(n) where n is number of nodes in the given binary tree.
Iterative approach using a stack:
Follow the below steps to implement the approach:
- Initializing a stack with a pair of the root node and its level, which is 0.
- While the stack is not empty, pop a pair from the top of the stack and process its node.
- If the current node is NULL, simply continue to the next iteration.
- If the current node’s level is equal to K, add its data to the result.
- Otherwise, push the current node’s right child onto the stack with its level incremented by 1, followed by the current node’s left child with its level incremented by 1.
- Finally, return the result vector containing all the nodes at a distance K from the root.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
};
Node* newNode( int data)
{
Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return node;
}
vector< int > Kdistance( struct Node* root, int k)
{
vector< int > result;
stack<pair<Node*, int > > s;
s.push(make_pair(root, 0));
while (!s.empty()) {
Node* curr = s.top().first;
int level = s.top().second;
s.pop();
if (curr == NULL) {
continue ;
}
if (level == k) {
result.push_back(curr->data);
}
s.push(make_pair(curr->right, level + 1));
s.push(make_pair(curr->left, level + 1));
}
return result;
}
int main()
{
Node* root = newNode(10);
root->left = newNode(10);
root->right = newNode(4);
root->left->left = newNode(4);
root->left->right = newNode(10);
int k = 1;
vector< int > result = Kdistance(root, k);
if (result.empty()) {
cout << "No nodes found at distance " << k
<< " from the root.\n" ;
}
else {
cout << "Nodes at distance " << k
<< " from the root: " ;
for ( int i = 0; i < result.size(); i++) {
cout << result[i] << " " ;
}
cout << endl;
}
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.Stack;
class Node {
int data;
Node left, right;
Node( int data) {
this .data = data;
this .left = this .right = null ;
}
}
public class Main {
static ArrayList<Integer> Kdistance(Node root, int k) {
ArrayList<Integer> result = new ArrayList<>();
Stack<Object[]> stack = new Stack<>();
stack.push( new Object[] { root, 0 });
while (!stack.isEmpty()) {
Object[] pair = stack.pop();
Node curr = (Node) pair[ 0 ];
int level = ( int ) pair[ 1 ];
if (curr == null ) {
continue ;
}
if (level == k) {
result.add(curr.data);
}
stack.push( new Object[] { curr.right, level + 1 });
stack.push( new Object[] { curr.left, level + 1 });
}
return result;
}
public static void main(String[] args) {
Node root = new Node( 10 );
root.left = new Node( 10 );
root.right = new Node( 4 );
root.left.left = new Node( 4 );
root.left.right = new Node( 10 );
int k = 1 ;
ArrayList<Integer> result = Kdistance(root, k);
if (result.isEmpty()) {
System.out.println( "No nodes found at distance " + k + " from the root." );
} else {
System.out.print( "Nodes at distance " + k + " from the root: " );
for ( int i = 0 ; i < result.size(); i++) {
System.out.print(result.get(i) + " " );
}
System.out.println();
}
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self .left = self .right = None
def newNode(data):
node = Node(data)
return node
def Kdistance(root, k):
result = []
stack = []
stack.append((root, 0 ))
while stack:
curr, level = stack.pop()
if curr is None :
continue
if level = = k:
result.append(curr.data)
stack.append((curr.right, level + 1 ))
stack.append((curr.left, level + 1 ))
return result
root = newNode( 10 )
root.left = newNode( 10 )
root.right = newNode( 4 )
root.left.left = newNode( 4 )
root.left.right = newNode( 10 )
k = 1
result = Kdistance(root, k)
if len (result) = = 0 :
print (f "No nodes found at distance {k} from the root." )
else :
print (f "Nodes at distance {k} from the root: {' '.join(map(str, result))}" )
|
C#
using System;
using System.Collections.Generic;
class Node
{
public int data;
public Node left, right;
public Node( int data)
{
this .data = data;
left = right = null ;
}
}
class BinaryTree
{
public static List< int > Kdistance(Node root, int k)
{
List< int > result = new List< int >();
Stack<Tuple<Node, int >> s = new Stack<Tuple<Node, int >>();
s.Push( new Tuple<Node, int >(root, 0));
while (s.Count > 0)
{
Tuple<Node, int > current = s.Pop();
Node curr = current.Item1;
int level = current.Item2;
if (curr == null )
{
continue ;
}
if (level == k)
{
result.Add(curr.data);
}
s.Push( new Tuple<Node, int >(curr.right, level + 1));
s.Push( new Tuple<Node, int >(curr.left, level + 1));
}
return result;
}
static void Main( string [] args)
{
Node root = new Node(10);
root.left = new Node(10);
root.right = new Node(4);
root.left.left = new Node(4);
root.left.right = new Node(10);
int k = 1;
List< int > result = Kdistance(root, k);
if (result.Count == 0)
{
Console.WriteLine( "No nodes found at distance " + k + " from the root." );
}
else
{
Console.Write( "Nodes at distance " + k + " from the root: " );
foreach ( int value in result)
{
Console.Write(value + " " );
}
Console.WriteLine();
}
}
}
|
Javascript
class Node {
constructor(data) {
this .data = data;
this .left = this .right = null ;
}
}
function newNode(data) {
let node = new Node(data);
return node;
}
function Kdistance(root, k) {
let result = [];
let stack = [];
stack.push([root, 0]);
while (stack.length > 0) {
let [curr, level] = stack.pop();
if (curr === null ) {
continue ;
}
if (level === k) {
result.push(curr.data);
}
stack.push([curr.right, level + 1]);
stack.push([curr.left, level + 1]);
}
return result;
}
let root = newNode(10);
root.left = newNode(10);
root.right = newNode(4);
root.left.left = newNode(4);
root.left.right = newNode(10);
let k = 1;
let result = Kdistance(root, k);
if (result.length === 0) {
console.log(`No nodes found at distance ${k} from the root.`);
} else {
console.log(`Nodes at distance ${k} from the root: ${result.join( ' ' )}`);
}
|
Output
Nodes at distance 1 from the root: 10 4
Time Complexity: O(N) , The time complexity of the iterative approach using a stack to find all nodes at a distance K from the root of a binary tree is O(N), where N is the number of nodes in the tree. This is because we need to visit every node in the tree exactly once to determine its level and add it to the result vector if its level is equal to K.
Auxiliary Space: O(N) , The auxiliary space complexity of this approach is also O(N), where N is the number of nodes in the tree. This is because we need to store information about each node in the stack until we process it, which requires O(N) space in the worst case for a completely unbalanced tree.
Please write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem.
Share your thoughts in the comments
Please Login to comment...