FIG Theory - complete binary tree determination -Check Completeness of a Binary Tree

2020-02-19 13:34:28

Problem Description:

 

Problem Solving:

Way is to use determined traversal sequence for a complete binary tree, the each non-empty before accessing the visited node can not be null.

    public boolean isCompleteTree(TreeNode root) {
        if (root == null) return true;
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        boolean flag = false;
        while (!q.isEmpty()) {
            int size = q.size();
            for (int k = 0; k < size; k++) {
                TreeNode curr = q.poll();
                if (curr != null) {
                    if (flag) return false;
                    q.add(curr.left);
                    q.add(curr.right);
                }
                else flag = true;
            }
        }
        return true;
    }

  

 

Guess you like

Origin www.cnblogs.com/hyserendipity/p/12330958.html