71、验证二叉搜索树

题目描述:
在这里插入图片描述

首先第一种简单的思路就是将中序遍历后的顺序放入list中,然后看是否时递增的,注意不能是相等,即前一个元素和后一个元素不能相等,代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isValidBST(TreeNode root) {
//		第一种解法:使用中序遍历
		List<Integer> tem = new ArrayList<>();
		ges(tem, root);
		if(root == null){
			return true;
		}
		int tems = tem.get(0);
		for (int i = 1; i < tem.size(); i++) {
			if(tems >= tem.get(i)){
				return false;
			}
			tems = tem.get(i);
		}
		return true;
		
    }
	public void ges(List<Integer> tem,TreeNode root){
		if(root == null){
			return ;
		}
		ges(tem, root.left);
		tem.add(root.val);
		ges(tem, root.right);
	}
}

第二种比较简单的就是使用递归,我们会发现左子树中的最大值都要小于根节点,右子树的最小值都要大于根节点,使用递归如下
效率明显得到了提升

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isValidBST(TreeNode root) {
Integer max = null;
		Integer min = null;
		if(root == null)
		return true;
		return ds(root, min, max);
		
    }
	public boolean ds(TreeNode root,Integer min, Integer max){
		if(root == null ){
			return true;
		}
		if(min != null && min >= root.val){
			return false;
		}
		if(max != null && max <= root.val ){
			return false;
		}
		return ds(root.left, min, root.val) && ds(root.right, root.val, max);
	}
	
}

猜你喜欢

转载自blog.csdn.net/qq_34446716/article/details/89165550