问题:
给定一个二叉树根节点,请你判断这棵树是不是二叉搜索树。
二叉搜索树满足每个节点的左子树上的所有节点均小于当前节点且右子树上的所有节点均大于当前节点。
最重要一点:二叉搜索排序树的中序遍历是单调升序的,因此只需要进行中序遍历判断即可
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return bool布尔型
*/
public boolean isValidBST (TreeNode root) {
// write code here
if (root==null){
return true;
}
ArrayList<Integer>a=new ArrayList<>();
inOrder(a,root);
for (int i=0;i<a.size()-1;i++){
if (a.get(i)>a.get(i+1)){
return false;
}
}
return true;
}
private static void inOrder(List<Integer> list, TreeNode root) {
if (root==null){
return;
}
inOrder(list,root.left);
list.add(root.val);
inOrder(list,root.right);
}
}