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.  
  15. /* Returns level of given data value */
  16. int getLevel(struct node *root, int data)
  17. {
  18. std::queue<struct node*> q;
  19. q.push(root);
  20. int level = 1;
  21. while(!q.empty()){
  22. q.push(NULL);
  23. while(q.front() != NULL){
  24. struct node *temp = q.front();
  25. q.pop();
  26. if(temp->data == data){
  27. return level;
  28. }
  29. if(temp->left){
  30. q.push(temp->left);
  31. }
  32. if(temp->right){
  33. q.push(temp->right);
  34. }
  35. }
  36. q.pop();
  37. level = level+1;
  38. }
  39. return 0;
  40. }
  41.  
  42. /* Utility function to create a new Binary Tree node */
  43. struct node* newNode(int data)
  44. {
  45. struct node *temp = new struct node;
  46. temp->data = data;
  47. temp->left = NULL;
  48. temp->right = NULL;
  49.  
  50. return temp;
  51. }
  52.  
  53. /* Driver function to test above functions */
  54. int main()
  55. {
  56. struct node *root = (struct node*)malloc(sizeof(struct node));
  57. int x;
  58.  
  59. /* Constructing tree given in the above figure */
  60. root = newNode(3);
  61. root->left = newNode(2);
  62. root->right = newNode(5);
  63. root->left->left = newNode(1);
  64. root->left->right = newNode(4);
  65.  
  66. for (x = 1; x <=5; x++)
  67. {
  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
 Level of 1 is 3
 Level of 2 is 2
 Level of 3 is 1
 Level of 4 is 3
 Level of 5 is 2