判断二叉搜索树的合法性

/*
 * 判断二叉搜索树的合法性
 * 二叉搜索树:左子树<=根>=右子树
 */
public class CheckBST {
    
    

	public static void main(String[] args) {
    
    
		TreeNode root = new TreeNode(5);
		root.left = new TreeNode(2);
		root.right = new TreeNode(6);
		root.left.left = new TreeNode(1);
		root.right.right = new TreeNode(7);
		root.left.right = new TreeNode(4);
		root.left.right.left = new TreeNode(3);
		boolean flag = isValidBST(root, null, null);
		System.out.println(flag);
		
	}
	static boolean isValidBST(TreeNode root, TreeNode min, TreeNode max) {
    
    
		if (root == null) return true;
		if (min != null && root.val <= min.val) return false;
		if (max != null && root.val >= max.val) return false;
		return isValidBST(root.left, min, root) && isValidBST(root.right, root, max);
	}

}

class TreeNode {
    
    
	int val;
	TreeNode left;
	TreeNode right;
	public TreeNode(int val) {
    
    
		this.val = val;
	}
	
}

猜你喜欢

转载自blog.csdn.net/qq_36986015/article/details/113700091