m2skills

nodes at k cpp

May 16th, 2018
24
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.49 KB | None | 0 0
  1. // program to print child nodes at distance k from the given node
  2.  
  3. #include <iostream>
  4. #include <queue>
  5. #include <map>
  6.  
  7. using namespace std;
  8.  
  9. // node class
  10. class node{
  11. public:
  12.     int data;
  13.     node* left;
  14.     node* right;
  15. };
  16.  
  17. // function that returns a pointer to new node
  18. node* createNode(int element){
  19.     node* temp = (node*) malloc(sizeof(node));
  20.     temp->data = element;
  21.     temp->left = NULL;
  22.     temp->right = NULL;
  23.     return temp;
  24. }
  25.  
  26.  
  27. // function to print child nodes at a distance k from the given node
  28. void print_nodes_at_K(node* root, int K){
  29.     if(root == NULL || K < 0){
  30.         return;
  31.     }
  32.     if(K == 0){
  33.         cout<<root->data<<" ";
  34.     }
  35.     if(K > -1) {
  36.         print_nodes_at_K(root->left, K - 1);
  37.         print_nodes_at_K(root->right, K - 1);
  38.     }
  39. }
  40.  
  41.  
  42. int main() {
  43.     node* head = createNode(1);
  44.     head->left = createNode(2);
  45.     head->right = createNode(3);
  46.     head->left->left = createNode(4);
  47.     head->left->right = createNode(5);
  48.     head->right->right = createNode(6);
  49.     head->left->left->right = createNode(7);
  50.     head->right->right->left = createNode(8);
  51.     head->left->left->right->left = createNode(9);
  52.     head->left->left->right->left->left = createNode(10);
  53.     head->right->right->left->right = createNode(11);
  54.     head->hd = 0;
  55.    
  56.     cout<<"Nodes at distance 2 from the root node are : ";
  57.     print_nodes_at_K(head, 2);
  58. }
  59.  
  60. /*
  61.  
  62. Nodes at distance 2 from the root node are : 4 5 6
  63. Process finished with exit code 0
  64.  
  65. */
Add Comment
Please, Sign In to add comment