一、题目
二、代码
/**
* 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
{
//数组 中序遍历 从小到大
boolean return_bool = true;
List<Integer> reverse_list = new LinkedList<>();
public void whether_search(TreeNode pro)
{
if(pro.left!=null) whether_search(pro.left);
reverse_list.add(pro.val);
if(pro.right!=null) whether_search(pro.right);
}
public boolean isValidBST(TreeNode root)
{
if(root == null) return_bool = false;
int i;
int length;
whether_search(root);
length = reverse_list.size();
for(i=1;i<length;i++)
{
if(reverse_list.get(i-1)>= reverse_list.get(i))
{
return_bool = false;
break;
}
}
return return_bool;
}
}
三、运行结果
四、附录
二刷
/**
* 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
{
//大部分二叉搜索树 可以存到list里面看大小
List< Integer > record = new LinkedList<>();
public void track(TreeNode pro)
{
if(pro == null ) return ;
if(pro.left!=null) track(pro.left);
record.add(pro.val);
if(pro.right!=null) track(pro.right);
}
public boolean isValidBST(TreeNode root)
{
track(root);
int i;
int length = record.size();
//for(i=0;i<length;i++) System.out.println(" "+record.get(i));
for(i=1;i<length;i++)
{
if(record.get(i)<=record.get(i-1)) return false;
}
return true;
}
}