How to determine whether a binary tree is complete?

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

    Thanks for @Jonathan Graehl 's pseudo code. I've implemented it in Java. I've tested it against iterative version. It works like a charm!

    public static boolean isCompleteBinaryTreeRec(TreeNode root){
    //      Pair notComplete = new Pair(-1, false);
    //      return !isCompleteBinaryTreeSubRec(root).equalsTo(notComplete);
        return isCompleteBinaryTreeSubRec(root).height != -1;
    }
    
    public static boolean isPerfectBinaryTreeRec(TreeNode root){
        return isCompleteBinaryTreeSubRec(root).isFull;
    }
    
    public static Pair isCompleteBinaryTreeSubRec(TreeNode root){
        if(root == null){
            return new Pair(0, true);
        }
    
        Pair left = isCompleteBinaryTreeSubRec(root.left);
        Pair right = isCompleteBinaryTreeSubRec(root.right);
    
        if(left.isFull && left.height==right.height){
            return new Pair(1+left.height, right.isFull);
        }
    
        if(right.isFull && left.height==right.height+1){
            return new Pair(1+left.height, false);
        }
    
        return new Pair(-1, false);
    }
    
    private static class Pair{
        int height;         
        boolean isFull;     
    
        public Pair(int height, boolean isFull) {
            this.height = height;
            this.isFull = isFull;
        }
    
        public boolean equalsTo(Pair obj){
            return this.height==obj.height && this.isFull==obj.isFull;
        }
    }
    

提交回复
热议问题