判断完全二叉树-JAVA
判断一个树是否属于完全二叉树可以从以下2个条件来判断:
-层次遍历二叉树
- 1 任何一个结点如果右孩子不为空,左孩子却是空,则一定不是完全二叉树
- 2 当一个结点出现右孩子为空时候,判断该结点的层次遍历后继结点是否为叶子节点,如果全部都是叶子节点,则是完全二叉树,如果存在任何一个结点不是叶节点,则一定不是完全二叉树。
class Tree{
int value;
Tree left;
Tree right;
public Tree(int value) {
this.value = value;
}
}
public class Code04 {
public static boolean isCBT(Tree tree) {
if(null == tree) {
return false;
}
Tree leftChild = null;
Tree rightChild = null;
boolean left = false;
Queue<Tree> queue = new LinkedList<Tree>();
queue.offer(tree);
while(!queue.isEmpty()) {
Tree head = queue.poll();
leftChild = head.left;
rightChild = head.right;
if((null != rightChild && null == leftChild) //右孩子不等于空,左孩子等于空 -> false
||
(left && (null != rightChild || null != leftChild)) //开启叶节点判断标志位时,如果层次遍历中的后继结点不是叶节点 -> false
) {
return false;
}
if(null != leftChild) {
queue.offer(leftChild);
}
if(null != rightChild) {
queue.offer(rightChild);
}else {
left = true;
}
}
return true;
}