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

判断平衡二叉树

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;
			
		}

猜你喜欢

转载自blog.csdn.net/qq_42403295/article/details/88759920