public static class Node {
public int value;
public Node left;
public Node right;
public Node(int data) {
this.value = data;
}
}
/**
* 判断一棵树是否是完全二叉树
* 分两种情况:
* 1.某个节点只有右孩子,没有左孩子;
* 2.某个节点左右孩子不全,但是后面依然出现了其它非叶子节点
* @param head
* @return
*/
public static boolean isCBT(Node head){
if (head == null){
return true;
}
Queue<Node> queue = new LinkedList<>();
queue.add(head);
Node l = null;
Node r = null;
//是否有节点左右孩子不全的
boolean leaf = false;
while (!queue.isEmpty()){
head = queue.poll();
l = head.left;
r = head.right;
if (
(l == null && r != null)
||
(leaf && (l != null || r != null))
){
return false;
}
if (l != null){
queue.add(l);
}
if (r != null){
queue.add(r);
}
if (l == null || r == null){
leaf = true;
}
}
return true;
}