How to determine whether a binary tree is complete?

前端 未结 16 1362
渐次进展
渐次进展 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:59
    bool isComplete (struct Node* root){
        if(root==NULL)
        return true;                  // Recur for left and right subtree 
        bool flag=false;
        int option1=height(root->left);
        int option2=height(root->right);
        if(option1==option2||option1==option2+1)
        flag=true;
        return flag&&isComplete(root->left)&&isComplete(root->right);
        }
    

    please consider as a correct answer if you found useful.

    0 讨论(0)
  • 2021-01-02 20:01

    The simplest procedure is:

    1. Find depth of the tree (simple algorithm).
    2. Count the number of nodes in a tree (by traversing and increasing the counter by one on visiting any node).
    3. For a complete binary tree of level d number of nodes equals to pow(2,d+1)-1.

    If condition satisfy tree, is complete binary tree, else not.

    That's a simple algorithm and turning it into a working code shouldn't be a problem if you are good enough coder.

    0 讨论(0)
  • 2021-01-02 20:02

    You could combine three pieces of information from the subtrees:

    • Whether the subtree is complete

    • The maximal height

    • The minimal height (equal to maximal height or to maximal height - 1)

    0 讨论(0)
  • 2021-01-02 20:02
    private static boolean isCompleteBinaryTree(TreeNode root) {
    
    if (root == null) {
        return false;
    } else {
        boolean completeFlag = false;
        List<TreeNode> list = new ArrayList<TreeNode>();
        list.add(root);
        while (!list.isEmpty()) {
            TreeNode element = list.remove(0);
            if (element.left != null) {
                if (completeFlag) {
                    return false;
                }
            list.add(element.left);
            } else {
                completeFlag = true;
            }
            if (element.right != null) {
                if (completeFlag) {
                    return false;
                }
            list.add(element.right);
            } else {
                completeFlag = true;
            }
        }
            return true;
        }
    }
    

    Reference: Check the following link for a detailed explanation http://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-complete-tree-or-not/

    0 讨论(0)
提交回复
热议问题