m2skills

width bt cpp

May 16th, 2018
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.98 KB | None | 0 0
  1. // program to find maximum width of a given binary tree
  2.  
  3. #include <iostream>
  4. #include <queue>
  5. using namespace std;
  6.  
  7. // node class
  8. class node{
  9. public:
  10.     int data;
  11.     node* left;
  12.     node* right;
  13. };
  14.  
  15. // function that returns a pointer to new node
  16. node* createNode(int element){
  17.     node* temp = (node*) malloc(sizeof(node));
  18.     temp->data = element;
  19.     temp->left = NULL;
  20.     temp->right = NULL;
  21.     return temp;
  22. }
  23.  
  24. // function to print the width of the binary tree
  25. int width(node* root){
  26.     if(root == NULL){
  27.         return 0 ;
  28.     }
  29.  
  30.     // creating a Queue for storing node for level wise traversal
  31.     queue<node *> Q;
  32.     Q.push(root);
  33.     int result = 0;
  34.  
  35.     while(!Q.empty()){
  36.         // store the current size of the Q
  37.         int count = Q.size();
  38.  
  39.         // find out the max width
  40.         result = max(result, count);
  41.  
  42.         while(count--) {
  43.             // pop the first node from the queue
  44.             node *NODE = Q.front();
  45.             Q.pop();
  46.  
  47.             // push the left child on queue
  48.             if (NODE->left != NULL) {
  49.                 Q.push(NODE->left);
  50.             }
  51.  
  52.             // push the right child on queue
  53.             if (NODE->right != NULL) {
  54.                 Q.push(NODE->right);
  55.             }
  56.         }
  57.     }
  58.  
  59.     // return the final width
  60.     return result;
  61. }
  62.  
  63. int main() {
  64.     node* head = createNode(1);
  65.     head->left = createNode(2);
  66.     head->right = createNode(3);
  67.     head->left->left = createNode(4);
  68.     head->left->right = createNode(5);
  69.     head->right->right = createNode(6);
  70.     head->left->left->right = createNode(7);
  71.     head->right->right->left = createNode(8);
  72.     head->left->left->right->left = createNode(9);
  73.     head->left->left->right->left->left = createNode(10);
  74.     head->right->right->left->right = createNode(11);
  75.  
  76.     cout<<"Width of the above binary tree is : "<<width(head)<<endl;
  77.  
  78. }
  79.  
  80.  
  81.  
  82. /*
  83.  
  84. Width of the above binary tree is : 3
  85. Process finished with exit code 0
  86.  
  87. */
Add Comment
Please, Sign In to add comment