Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // program to find maximum width of a given binary tree
- #include <iostream>
- #include <queue>
- using namespace std;
- // node class
- class node{
- public:
- int data;
- node* left;
- node* right;
- };
- // function that returns a pointer to new node
- node* createNode(int element){
- node* temp = (node*) malloc(sizeof(node));
- temp->data = element;
- temp->left = NULL;
- temp->right = NULL;
- return temp;
- }
- // function to print the width of the binary tree
- int width(node* root){
- if(root == NULL){
- return 0 ;
- }
- // creating a Queue for storing node for level wise traversal
- queue<node *> Q;
- Q.push(root);
- int result = 0;
- while(!Q.empty()){
- // store the current size of the Q
- int count = Q.size();
- // find out the max width
- result = max(result, count);
- while(count--) {
- // pop the first node from the queue
- node *NODE = Q.front();
- Q.pop();
- // push the left child on queue
- if (NODE->left != NULL) {
- Q.push(NODE->left);
- }
- // push the right child on queue
- if (NODE->right != NULL) {
- Q.push(NODE->right);
- }
- }
- }
- // return the final width
- return result;
- }
- int main() {
- node* head = createNode(1);
- head->left = createNode(2);
- head->right = createNode(3);
- head->left->left = createNode(4);
- head->left->right = createNode(5);
- head->right->right = createNode(6);
- head->left->left->right = createNode(7);
- head->right->right->left = createNode(8);
- head->left->left->right->left = createNode(9);
- head->left->left->right->left->left = createNode(10);
- head->right->right->left->right = createNode(11);
- cout<<"Width of the above binary tree is : "<<width(head)<<endl;
- }
- /*
- Width of the above binary tree is : 3
- Process finished with exit code 0
- */
Add Comment
Please, Sign In to add comment