LeetCode OJ 98. Validate Binary Search Tree

时间:2022-08-12 21:48:16

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

判断一棵二叉树是否是二叉搜索树,我们可以采用中序遍历来看二叉树的中序遍历是否是递增的,如果是递增的,那么就是BST,如果不是递增的,那么就不是BST。

代码如下:

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public long n = (long)Integer.MIN_VALUE-1;
public boolean isValidBST(TreeNode root) {
if(root == null) return true;
boolean a = isValidBST(root.left);
if(root.val<=n) return false;
else n = root.val;
boolean b = isValidBST(root.right);
return (a&&b);
}
}