How to determine whether a binary tree is complete?

前端 未结 16 1691
渐次进展
渐次进展 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 20:02

    private static boolean isCompleteBinaryTree(TreeNode root) {
    
    if (root == null) {
        return false;
    } else {
        boolean completeFlag = false;
        List list = new ArrayList();
        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/

提交回复
热议问题