fork download
  1. #include<iostream>
  2. #include<cstdlib>
  3. #include<cstdio>
  4. #include<queue>
  5. using namespace std;
  6. /* A tree node structure */
  7. struct node
  8. {
  9. int data;
  10. struct node *left;
  11. struct node *right;
  12. };
  13.  
  14. /* Returns level of given data value */
  15. int getLevel(struct node *root, int data)
  16. {
  17. std::queue<struct node*> q;
  18. q.push(root);
  19. int level = 1;
  20. while(!q.empty()){
  21. q.push(NULL);
  22. while(q.front() != NULL){
  23. struct node *temp = q.front();
  24. q.pop();
  25. if(temp->data == data){
  26. return level;
  27. }
  28. if(temp->left){
  29. q.push(temp->left);
  30. }
  31. if(temp->right){
  32. q.push(temp->right);
  33. }
  34. }
  35. q.pop();
  36. level = level+1;
  37. }
  38. return 0;
  39. }
  40.  
  41. /* Utility function to create a new Binary Tree node */
  42. struct node* newNode(int data)
  43. {
  44. struct node *temp = new struct node;
  45. temp->data = data;
  46. temp->left = NULL;
  47. temp->right = NULL;
  48.  
  49. return temp;
  50. }
  51.  
  52. /* Driver function to test above functions */
  53. int main()
  54. {
  55. struct node *root = (struct node*)malloc(sizeof(struct node));
  56. int x;
  57.  
  58. /* Constructing tree given in the above figure */
  59. root = newNode(3);
  60. root->left = newNode(2);
  61. root->right = newNode(5);
  62. root->left->left = newNode(1);
  63. root->left->right = newNode(4);
  64.  
  65. /* for (x = 1; x <=5; x++)
  66. {*/
  67. x= 7;
  68. int level = getLevel(root, x);
  69. if (level)
  70. printf(" Level of %d is %d\n", x, getLevel(root, x));
  71. else
  72. printf(" %d is not present in tree \n", x);
  73.  
  74. // }
  75.  
  76. getchar();
  77. return 0;
  78. }
  79.  
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
 7 is not present in tree