Skip to content

Commit be94b70

Browse files
authored
Print nodes at k distance from root
1 parent 9c4e906 commit be94b70

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

Tree/kdist.cpp

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#include<bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
class node
6+
{
7+
public:
8+
int data;
9+
node* left;
10+
node* right;
11+
12+
node(int data)
13+
{
14+
this->data = data;
15+
this->left = NULL;
16+
this->right = NULL;
17+
}
18+
};
19+
20+
void printKDistant(node *root , int k)
21+
{
22+
if(root == NULL|| k < 0 )
23+
return;
24+
if( k == 0 )
25+
{
26+
cout << root->data << " ";
27+
return;
28+
}
29+
30+
printKDistant( root->left, k - 1 ) ;
31+
printKDistant( root->right, k - 1 ) ;
32+
33+
}
34+
35+
36+
int main()
37+
{
38+
39+
40+
node *root = new node(1);
41+
root->left = new node(2);
42+
root->right = new node(3);
43+
root->left->left = new node(4);
44+
root->left->right = new node(5);
45+
root->right->left = new node(8);
46+
47+
printKDistant(root, 2);
48+
return 0;
49+
}

0 commit comments

Comments
 (0)