判断是否搜索二叉树

1.数据的准备

 

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

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

2.使用数组的方式判断

    /**
	 *  use container
	 * @param head
	 * @return
	 */
	public static boolean isSearch1(Node head) {
		if(head == null){
			return true;
		}
		ArrayList<Node> nodes = new ArrayList<>();
		in(head,nodes);
		for (int i = 0; i < nodes.size() - 1; i++) {
			if(nodes.get(i).value >= nodes.get(i + 1).value){
				return false;
			}
		}
		return true;
	}

	/**
	 * middle traversal
	 * @param head
	 * @param arr
	 */
	public static void in(Node head, ArrayList<Node> arr) {
		if(head == null){
			return;
		}
		in(head.left,arr);
		arr.add(head);
		in(head.right,arr);
	}

3.不使用数组的方式实现

 

    /**
	 * middle traversal
	 * @param head
	 * @param arr
	 */
	public static void in(Node head, ArrayList<Node> arr) {
		if(head == null){
			return;
		}
		in(head.left,arr);
		arr.add(head);
		in(head.right,arr);
	}

	/**
	 * prepare data Object
	 */
	public static class Info {
		private int max;
		private int min;
		private boolean isSearch;
		public Info(int mx,int mn,boolean isS){
			max = mx;
			min = mn;
			isSearch = isS;
		}
	}

	/**
	 * nonuse container
	 * @param head
	 * @return
	 */
	public static boolean isSearch2(Node head) {
		if(head == null){
			return true;
		}
		return process(head).isSearch;
	}

	/**
	 * core code
	 * @param head
	 * @return
	 */
	public static Info process(Node head) {
		if(head == null){
			return null;
		}
		// ====== prepare ======
		Info leftInfo = process(head.left);
		Info rightInfo = process(head.right);
		int max = head.value, min = head.value;
		boolean isSearch = true;
		// ====== prepare end ======

		//===== find the maximum and minimum ======
		if(leftInfo != null){
			max = Math.max(max,leftInfo.max);
		}
		if(rightInfo != null){
			min = Math.min(min,rightInfo.min);
		}
		if(rightInfo != null){
			max = Math.max(max,rightInfo.max);
		}
		if(leftInfo != null){
			min = Math.min(min,leftInfo.min);
		}
		//===== find the maximum and minimum end ======

		// ======= check =======
		if(leftInfo != null){
			if(leftInfo.max >= head.value || !leftInfo.isSearch){
				isSearch = false;
			}
		}
		if(rightInfo != null){
			if(rightInfo.min <= head.value || !rightInfo.isSearch){
				isSearch = false;
			}
		}
		// ======= check end =======

		return new Info(max,min,isSearch);
	}

 总结:

 1.当左子树的值比当前节点大
 2.当右子树的值比当前的节点小
 3.以上两种情况可判断为不是搜索二叉树

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值