递归
一个有效的二叉搜索树中序遍历应该是一个递增序列
java
/**
* 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;
* }
* }
*/
class Solution {
ArrayList<Integer> array = new ArrayList<>();
public boolean isValidBST(TreeNode root) {
inOrder(root);
for(int i = 1; i < array.size(); i++){
if(array.get(i) <= array.get(i - 1)){
return false;
}
}
return true;
}
// 中序遍历
public void inOrder(TreeNode root){
if(root == null){
return ;
}
inOrder(root.left);
array.add(root.val);
inOrder(root.right);
}
}