Tree_Graph Validate Binary Search Tree 检测一个BST是否有效 @CareerCup

本文介绍了三种方法来验证一个二叉树是否为二叉搜索树(BST),包括中序遍历、中序遍历优化版和最小最大限制法。通过实例演示了每种方法的实现和应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Implement a function to check if a binary tree is a binary search tree

判断一个二叉树是否是BST


思路:

1)中序遍历二叉树,把结果放在一个数组里。然后判断这个数组是否递增

2)在上一种方法的基础上优化,无需用到数组。在中序遍历时与上一个数比较,判断是否恒递增

3)我最喜欢的方法:min max的方法,限定每一个元素的上下限,如果超出范围则为false

参考LeetCode原题:http://blog.youkuaiyun.com/fightforyourdream/article/details/14444883


package Tree_Graph;

import CtCILibrary.TreeNode;

public class S4_5 {

	// =============================== checkBST 方法1,中序遍历建数组
	public static int index = 0;
	
	public static boolean checkBST(TreeNode root, int size) {
		int[] A = new int[size];
		copyBST(root, A);
		for(int i=1; i<A.length; i++) {
			if (A[i] <= A[i-1]) {
				return false;
			}
		}
		return true;
	}
	
	public static void copyBST(TreeNode root, int[] A) {
		if (root == null) {
			return;
		}
		
		copyBST(root.left, A);
		A[index++] = root.data;
		copyBST(root.right, A);
	}
	
	
	// =============================== checkBST 方法2,中序遍历但仅保留last变量
	public static int last = Integer.MIN_VALUE;
	
	public static boolean checkBST2(TreeNode root) {
		if(root == null) {
			return true;
		}
		
		if( !checkBST2(root.left) ) {		// 检测左子树
			return false;
		}
		if(root.data <= last) {				// 检查当前节点,如果有序则必然比last大
			return false;
		}
		last = root.data;						// 更新last节点
		
		if( !checkBST2(root.right) ) {		// 检查右子树
			return false;
		}
		
		return true;
	}
	
	
	
	// =============================== checkBST 方法3,Min-Max
	// Time: O(N), space: O(logN)
	public static boolean checkBST3(TreeNode root) {
		return checkBSTRec(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
	}
	
	public static boolean checkBSTRec(TreeNode root, int min, int max) {
		if (root == null) {
			return true;
		}
		// 当前节点非BST
		if(root.data<=min || root.data>max) {
			return false;
		}
		
		// 左子树或者右子树非BST
		if( !checkBSTRec(root.left, min, root.data) || !checkBSTRec(root.right, root.data, max)) {
			return false;
		}
		
		return true;
	}
	
	
	public static void main(String[] args) {
		int[] array = {3, 5, 6, 10, 13, 15};
//		int[] array = {3, 5, 6};
		TreeNode node = TreeNode.createMinimalBST(array);
		node.print();
		System.out.println(checkBST(node, array.length));
		System.out.println(checkBST2(node));
		System.out.println(checkBST3(node));
	}
	
}







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值