判断是否是完全二叉树(JAVA)

判断完全二叉树-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;
	}
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值