How to determine whether a binary tree is complete?

前端 未结 16 1620
渐次进展
渐次进展 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

    Here is a C code for checking if the binary tree is complete:

    struct node
    {
        int data;
        struct node * left;
        struct node * right;
    };
    int flag;
    int isComplete(struct node *root, int depth)
    {
        int ld, rd;
        if (root==NULL) return depth;
        else
        {
            ld =  isComplete(root->left,depth+1);
            rd = isComplete(root->right, depth+1);
            if (ld==-1 || rd==-1) return -1;
            else if (ld==rd) return ld;
            else if (ld==rd-1 && flag==0)
            {
                flag=1;
                return rd;
            }
            else return -1;
        }
    }
    

    The way it works is:

    • If the depth of left subtree is same as depth of right subtree, it returns the depth up the hirearchy.

    • if the depth of left subtree is one more than the depth of right subtree, it returns depth of right subtree up the hirarchy and enables the flag.

    • If it finds that the depth of left subtree and right subtree and flag is already set, it returns -1 up the hierarchy.

    • In the end, if the function returns -1, it is not the complete subtree, else the value returned is the minimum depth of the tree.

提交回复
热议问题