JAVA-如何判断二叉树是完全二叉树

61 篇文章 3 订阅

思路

  • 基本是层序遍历的思路
  • 完全二叉树判断逻辑:
    两个标识:flag标识是否是完全二叉树,isLeaf标识是否遍历到叶子结点
 1. 若一个结点无左孩子有右孩子,置flag为false
 2. 当一个结点无右孩子时,说明这个结点以后的结点一定是叶子结点,将叶子结点标识isLeaf置为true
 3. 当isLeaf为true时,若一个结点有子结点,则flag置为false

以上逻辑判断先后顺序不能改变,尤其是第一句与第三句

代码

// 层序遍历顺便判断完全二叉树
		public void level() {
			LinkedList<Node> list = new LinkedList<Node>();
			list.add(root);
			String result = "";
			boolean isLeaf = false;
			boolean flag = true;
			while (list.size() > 0) {
				Node temp = list.remove();
				result = result + temp.key + " ";
				// 层序遍历
				if (temp.leftChild != null)
					list.add(temp.leftChild);
				if (temp.rightChild != null)
					list.add(temp.rightChild);
				// 判断完全二叉树
				if (isLeaf && (temp.leftChild != null || temp.rightChild != null))  //语句块A
					flag = false;													//语句块A
				if (temp.leftChild == null && temp.rightChild != null)
					flag = false;
				if (temp.rightChild == null)//一定要放在语句块A后面
					isLeaf = true;
			}
			System.out.println(result.trim());
			if (flag)
				System.out.println("YES");
			else
				System.out.println("NO");
		}
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值