Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1e0641e

Browse files
Create Print nodes at distance k from node
1 parent e8949f8 commit 1e0641e

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/**********************************************************
2+
3+
Following is the Binary Tree Node class structure
4+
5+
template <typename T>
6+
class BinaryTreeNode {
7+
public :
8+
T data;
9+
BinaryTreeNode<T> *left;
10+
BinaryTreeNode<T> *right;
11+
12+
BinaryTreeNode(T data) {
13+
this -> data = data;
14+
left = NULL;
15+
right = NULL;
16+
}
17+
};
18+
19+
***********************************************************/
20+
void printnodesatdepth(BinaryTreeNode<int>* root,int depth){
21+
if(root==NULL){
22+
return;
23+
}
24+
if(depth==0){
25+
cout<<root->data<<endl;
26+
return;
27+
}
28+
printnodesatdepth(root->left,depth-1);
29+
printnodesatdepth(root->right,depth-1);
30+
}
31+
int print(BinaryTreeNode<int>* root,int k,int element){
32+
if(root==NULL){
33+
return -1;
34+
}
35+
if(root->data==element){
36+
printnodesatdepth(root,k);
37+
return 0;
38+
}
39+
int ld=print(root->left,k,element);
40+
if(ld!=-1){
41+
if(ld+1==k){
42+
cout<<root->data<<" ";
43+
return ld+1;
44+
}
45+
else{
46+
printnodesatdepth(root->right,k-ld-2);
47+
return ld+1;
48+
}
49+
}
50+
else{
51+
int rd=print(root->right,k,element);
52+
if(rd==-1){
53+
return -1;
54+
}
55+
else if(rd+1==k){
56+
cout<<root->data<<endl;
57+
return rd+1;
58+
}
59+
else{
60+
printnodesatdepth(root->left,k-rd-2);
61+
return rd+1;
62+
}
63+
}
64+
}
65+
void nodesAtDistanceK(BinaryTreeNode<int> *root, int node, int k) {
66+
if(root==NULL){
67+
return;
68+
}
69+
int ans=print(root,k,node);
70+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /