判断一棵树是否是搜索二叉树、判断一棵树是否是完全二叉树

判断一棵树是否是搜索二叉树、判断一棵树是否是完全二叉树

判断是否是搜索二叉树的思路:如果一颗二叉树在中序遍历过程中出现了当前结点的值比前一节点值小,这说明不是搜索二叉树。

判断是否是完全二叉树的思路:1)如果一个结点有右孩子无左孩子一定不是完全二叉树

​ 2)如果一个结点不是左右两个孩子都有(有左孩子无右孩子,左右孩子都没有),那么后面遇到的节点都必须是叶节点。

public class IsBSTAndCBT {
	public static class Node {
		public int value;
		public Node left;
		public Node right;

		public Node(int value) {
			this.value = value;
		}
	}

	/*
	 * 判断是否是搜索二叉树的思路:如果一颗二叉树在中序遍历过程中出现了当前结点的值比前一节点值小,这说明不是搜索二叉树。
	 */
	public static boolean isBST(Node head) {
		if (head != null) {
			Stack<Node> stack = new Stack<Node>();
			int pre = Integer.MIN_VALUE;
			while (!stack.isEmpty() || head != null) {
				if (head != null) {
					stack.push(head);
					head = head.left;
				} else {
					head = stack.pop();
					if (head.value < pre) {
						return false;
					}
					pre = head.value;
					head = head.right;
				}
			}
		}
		return true;
	}

	/*
	 * 判断是否是完全二叉树的思路:1)如果一个结点有右孩子无左孩子一定不是完全二叉树
	 * 
	 * 2)如果一个结点不是左右两个孩子都有(有左孩子无右孩子,左右孩子都没有),那么后面遇到的节点都必须是叶节点。
	 * 
	 */
	public static boolean isCBT(Node head) {
		if (head == null) {
			return true;
		}
		Queue<Node> queue = new LinkedList<Node>();
		queue.offer(head);
		boolean leaf = false;
		Node l = null;
		Node r = null;
		while (!queue.isEmpty()) {
			head = queue.poll();
			l = head.left;
			r = head.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;
			}
		}
		return true;
	}

猜你喜欢

转载自blog.csdn.net/gkq_tt/article/details/86149017