判断平衡二叉树、搜索二叉树、完全二叉树

判断平衡二叉树

public static int isBalance(Node head) {
		if(head==null)
			return 0;
		int left=isBalance(head.left)+1;
		int right=isBalance(head.right)+1;
		if(Math.abs(left-right)>1||left==-1||right==-1)
			return -1;
		return Math.max(left, right)+1;
	}

判断搜索二叉树
搜索二叉树是严格的左子树小于根,右子树大于根
搜索二叉树的中序遍历是升序的,就是搜索二叉树

public static boolean inOrder(Node head) {
		if(head==null)
			return true;
		int pre=Integer.MIN_VALUE;
		Stack<Node> stack=new Stack<>();
		stack.push(head);
		while(!stack.isEmpty()||head!=null) {
			if(head!=null) {
				stack.push(head);
				head=head.left;
			}
			else {
				head=stack.pop();
				if(pre<head.value) {
					pre=head.value;
				}
				else if(pre>head.value){
					return false;
				}
				head=head.right;
			}
		}
		return true;
	}

判断完全二叉树

按层遍历来判断,用一个布尔值work,当当前节点的左节点或者右节点出现null时,把work设置为false,继续按层遍历中,若发现有非空的节点,则查看work是否为false,是的话表示前面已经出现了空节点,则返回false。

//判断完全二叉树
		public static boolean ByLevel(Node head) {
			if(head==null)
				return true;
			boolean work=true;
			Queue<Node> queue=new LinkedList<>();
			queue.offer(head);
			while(!queue.isEmpty()) {
				head=queue.poll();
				//if(head.left==null&&head.right!=null){
				//		return false;
				//}
				if(head.left!=null) {
					queue.offer(head.left);
					if(work==false)
						return false;
				}
				else
					work=false;
				if(head.right!=null) {
					queue.offer(head.right);
					if(work==false)
						return false;
				}
				else
					work=false;
			}
			return true;
			
		}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值