How to determine whether a binary tree is complete?

前端 未结 16 1688
渐次进展
渐次进展 2021-01-02 19:15

A complete binary tree is defined as a binary tree in which every level, except possibly the deepest, is completely filled. At deepest level, all nodes must be as far left a

16条回答
  •  悲哀的现实
    2021-01-02 19:57

    You can also solve this problem by using level order traversal. The procedure is as follows:

    1. Store the data element of the nodes encountered in a vector
    2. If the node is NULL, then store a special number(INT_MIN)
    3. Keep track of the last non-null node visited - lastentry
    4. Now traverse the vector till lastentry. If you ever encounter INT_MIN, then the tree is not complete. Else it is a complete binary tree.

    Here is a c++ code:

    My tree node is:

    struct node{
        int data;
        node *left, *right;
    };
    
    void checkcomplete(){//checks whether a tree is complete or not by performing level order traversal
        node *curr = root;
        queue Q;
        vector arr;
        int lastentry = 0;
        Q.push(curr);
        int currlevel = 1, nextlevel = 0;
        while( currlevel){
            node *temp = Q.front();
            Q.pop();
            currlevel--;
            if(temp){
                arr.push_back(temp->data);
                lastentry = arr.size();
                Q.push(temp->left);
                Q.push(temp->right);
                nextlevel += 2;
            }else
                arr.push_back(INT_MIN);
            if(!currlevel){
                currlevel = nextlevel;
                nextlevel = 0;
            }
        }
        int flag = 0;
        for( int i = 0; i

提交回复
热议问题