【Leetcode】98. 验证二叉搜索树

117 阅读1分钟

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

// 98. 验证二叉搜索树

// 给定一个二叉树,判断其是否是一个有效的二叉搜索树。

// 假设一个二叉搜索树具有如下特征:

// 节点的左子树只包含小于当前节点的数。
// 节点的右子树只包含大于当前节点的数。
// 所有左子树和右子树自身必须也是二叉搜索树。

题解

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
 
// 非递归的中序遍历
// 
// BST的中序遍历是升序的。构建一个pre保存上一次结点的值,注意这里一定要设置成
// double pre = -Double.MAX_VALUE,测试用例会卡这个点。
// 在中序遍历取值时,将当前指针指向结点的值与pre对比,如果上一个结点值pre
// 居然大于等于当前结点值cur.cal,直接返回false,否则,递归结束返回true。
class Solution {
	double pre = -Double.MAX_VALUE;
	
    public boolean isValidBST(TreeNode root) {
		return inOrderNR(root);
	}
	
	private boolean inOrderNR(TreeNode root) {
		TreeNode cur = root;
		Stack<TreeNode> stack = new Stack<>();
		
		while (cur != null || !stack.isEmpty()) {
			while (cur != null) {
				stack.push(cur);
				cur = cur.left;
			}
			cur = stack.pop();
			if (cur.val <= pre)
				return false;
			pre = cur.val;
			cur = cur.right;
		}
		return true;
	}
}



// 递归的中序遍历
// 意思是一样的。
// 执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
// 内存消耗:38.2 MB, 在所有 Java 提交中击败了45.27%的用户
class Solution {
	double pre = -Double.MAX_VALUE;
	boolean res = true;
	
    public boolean isValidBST(TreeNode root) {
		inOrder(root);
		return res;
	}
	
	private void inOrder(TreeNode root) {
		if (root == null)
			return;
		
		if (root.left != null)
			inOrder(root.left);
		if (root.val <= pre)
			res = false;
		pre = root.val;
		if (root.right != null)
			inOrder(root.right);
			
	}
}