核心思想:中序遍历
思路:
二叉搜索树的中序遍历是有序的,如果中序遍历结果不是递增的,则不是二叉搜索树。
/**
* 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 {
public boolean sign = true;
public boolean isValidBST(TreeNode root) {
List<Integer> list = new ArrayList<>();
zxbl(root,list);
if(list.size() == 0){
sign = true;
}else if(list.size() == 1){
sign = true;
}else{
for(int i = 1; i < list.size(); i++){
if(list.get(i) <= list.get(i - 1)){
sign = false;
}
}
}
return sign;
}
public void zxbl(TreeNode root,List list){
if(root != null){
zxbl(root.left,list);
list.add(root.val);
zxbl(root.right,list);
}
}
}
class Solution {
public boolean isValidBST(TreeNode root) {
Deque<TreeNode> deque = new ArrayDeque<>();
//int num = Integer.MIN_VALUE;
//这里题目用了INT的最小值进行测试了,所以用DOUBLE
//为什么不用DOUBLE.MIN_VALUE,因为这nm是个无线接近于0的数
double num = -Double.MAX_VALUE;
while(root != null || !deque.isEmpty()){
while(root != null){
deque.addLast(root);
root = root.left;
}
root = deque.pollLast();
if(root.val <= num){
return false;
}
num = root.val;
root = root.right;
}
return true;
}
}