判断一棵二叉树是否为搜索二叉树、完全二叉树、平衡二叉树(java)

平衡二叉树的解法:主要是求出二叉树的高度,若根节点的左子树的高度与右子树的高度差小于等于1,则表示该二叉树为平衡二叉树

public static class Node{
	public int value;
	public Node left;
	public Node right;
	public Node(int data){
		this.value = data;
	}
}
public static boolean isBalance(Node head){
	return getHeight(head, 0) ! = -1;
}

public static int getHeight(Node head, int level){
	if(head == null){
		return level;
	}
	int lh = getHeight(head.left, level + 1);
	int rh = getHeight(head.right, level + 1);
	if(lh == -1 || rh == -1 || Math.abs(lh - rh) > 1){
		return -1;
	}
}
完全二叉树的解法:若最左的一个节点只有一个左子节点,则其余的同高度的节点都应该是叶节点
public static boolean isComplete(Node head){
	if(head == null){
		return true;
	}
	Queue<Node> queue = new LinkedList<Node>();
	boolean leaf = false;
	Node cur = null;
	Node l = null;
	Node r = null;
	queue.offer(head);
	while(!queue.isEmpty){
		cur = queue.poll();
		l = cur.left;
		r = cur.right;
		if((leaf && (l != null || r != null)) || (l == null && r != null)){
			return false;
		}
		if(l != null){
			queue.offer(l);
		}
		if(r != null){
			queue.offer(r);
		}else{
			leaf = true;
		}
	}
}
搜索二叉树的解法:只需要中序遍历整棵二叉树,判断得到的节点序列是否为依次递增即可。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值