0
点赞
收藏
分享

微信扫一扫

Leetcode98. 验证二叉搜索树


题目传送:​​https://leetcode.cn/circle/discuss/KBNhF9/​​

运行效率:

Leetcode98. 验证二叉搜索树_二叉树


思路:

如果该二叉树是搜索二叉树的话,那我们对该二叉树进行中序遍历得到的结果一定是升序的

代码如下:
①第一种写法

long pre = Long.MIN_VALUE;

//如果该二叉树是搜索二叉树的话,那我们对该二叉树进行中序遍历得到的结果一定是升序的
public boolean isValidBST(TreeNode root) {
//处理边界情况
if(root==null){
return true;
}
//递归左子树
if(!isValidBST(root.left)){
return false;
}
if(root.val<=pre){
return false;
}
pre=root.val;
return isValidBST(root.right);
}

②第二种写法

List<Integer> list= new ArrayList();

//如果该二叉树是搜索二叉树的话,那我们对该二叉树进行中序遍历得到的结果一定是升序的
public boolean isValidBST(TreeNode root) {
inOrder(root);
for(int i=0;i<list.size()-1;i++){
if(list.get(i)>=list.get(i+1)){
return false;
}
}
return true;
}
/*
* @description: 中序遍历该二叉树
* @date: 2022/8/27 10:13
* @parm: a
* @retun: a
*/
public void inOrder(TreeNode root) {
//处理边界情况
if(root==null){
return;
}
if(root.left!=null){
inOrder(root.left);
}
list.add(root.val);

if(root.right!=null){
inOrder(root.right);
}
}


举报

相关推荐

0 条评论