LeetCode OJ 98. Validate Binary Search Tree

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。

代码如下:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public long n = (long)Integer.MIN_VALUE-1;
12     public boolean isValidBST(TreeNode root) {
13         if(root == null) return true;
14         boolean a = isValidBST(root.left);
15         if(root.val<=n) return false;
16         else n = root.val;
17         boolean b = isValidBST(root.right);
18         return (a&&b);
19     }
20 }
原文地址:https://www.cnblogs.com/liujinhong/p/5457777.html