fork(2) download
  1. #include <iostream>
  2. using namespace std;
  3. #define MAX_HEIGHT 1000
  4.  
  5. struct Node
  6. {
  7. int key;
  8. Node *left, *right;
  9. };
  10.  
  11. Node* newNode(int key)
  12. {
  13. Node* node = new Node;
  14. node->key = key;
  15. node->left = node->right = NULL;
  16. return (node);
  17. }
  18.  
  19. void kDistantFromLeafUtil(Node* node, int height[], int pathLen, int k)
  20. {
  21. if (node==NULL) return;
  22. height[pathLen] = node->key;
  23. pathLen--;
  24.  
  25. if(node->left == NULL && node->right == NULL){
  26. cout <<"For Node "<<node->key <<"K distance node is= "<< height[pathLen+k+1] << " "<<endl;
  27. return;
  28. }
  29. kDistantFromLeafUtil(node->left, height, pathLen, k);
  30. kDistantFromLeafUtil(node->right, height, pathLen, k);
  31. }
  32.  
  33. void printKDistantfromLeaf(Node* node, int k)
  34. {
  35. int height[MAX_HEIGHT];
  36. bool visited[MAX_HEIGHT] = {false};
  37. kDistantFromLeafUtil(node, height, 1000, k);
  38. }
  39.  
  40. int main()
  41. {
  42. Node * root = newNode(1);
  43. root->left = newNode(2);
  44. root->right = newNode(3);
  45. root->left->left = newNode(4);
  46. root->left->right = newNode(5);
  47. root->right->left = newNode(6);
  48. root->right->right = newNode(7);
  49. root->left->left->right = newNode(8);
  50. cout << "Nodes at distance 2 are: "<<endl;
  51. printKDistantfromLeaf(root, 2);
  52.  
  53. return 0;
  54. }
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
Nodes at distance 2 are: 
For Node 8K distance node is= 2 
For Node 5K distance node is= 1 
For Node 6K distance node is= 1 
For Node 7K distance node is= 1