|
| 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