/** * 完全二叉树:要么是满二叉树,要么是在满二叉树的基础上,最后一层的节点是从左到右是依次添加的 * 采用按层遍历的方式判断是不是完全二叉树 */ public class IsCompleteTree { public static void main(String[] args) { Node head = new Node(1); head.left = new Node(2); head.right = new Node(3); head.left.left = new Node(4); head.left.right = new Node(5); head.right.right = new Node(6); System.out.println(isCompleteTree(head)); } public static boolean isCompleteTree(Node head) { if (head == null) { return true; } LinkedList<Node> queue = new LinkedList<Node>(); queue.offer(head); Node left = null; Node right = null; boolean leaf = false; while (!queue.isEmpty()) { Node node = queue.poll(); left = node.left; right = node.right; // 左节点为空,右节点不为空 if (left == null && right != null) { return false; } // 当检查叶子节点状态开启时,但是又不是叶子节点时 if (leaf && (left != null || right != null)) { return false; } // 开启检查叶子节点状态 if ((left == null && right == null) || (left != null && right == null)) { leaf = true; } if (left != null) { queue.offer(left); } if (right != null) { queue.offer(right); } } return true; } public static class Node { Node left; Node right; int value; public Node(int value) { super(); this.value = value; } } }