Leetcode98. 验证二叉搜索树
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
有效 二叉搜索树定义如下:
节点的左子树只包含 小于 当前节点的数。
节点的右子树只包含 大于 当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
输入:root = [2,1,3]
输出:true
二叉搜索树的中序遍历是有序的,运用中序遍历判断
/**
* 二叉搜索树中序遍历是有序的
*
* @param root
* @return
*/
public static boolean isValidBST4(TreeNode root) {
Deque<TreeNode> stack = new LinkedList<>();
int a = Integer.MIN_VALUE;
while (!stack.isEmpty() || root != null) {
if (root != null) {
stack.push(root);
root = root.left;
} else {
TreeNode node = stack.pop();
// 如果中序遍历得到的节点的值小于等于前一个 inorder,说明不是二叉搜索树
if (node.value <= a) return false;
a = node.value;
root = node.right;
}
}
return true;
}