码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 98

时间:2020-05-05 11:01:33      阅读:48      评论:0      收藏:0      [点我收藏+]

标签:递归   arch   false   检查   get   http   arc   方法   存在   

https://leetcode-cn.com/problems/validate-binary-search-tree/

树题,没什么好说的,直接递归就完事了。

第一种,使用中序遍历将输出值保存在list中,然后检查这个list是否升序的就可以AC.不过这个方法比较慢,3ms,java上只击败了19.96%的人。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    ArrayList<Integer> list;
    public boolean isValidBST(TreeNode root) {
        if(root == null){
            return true;
        }
        list = new ArrayList<>();
        dfs(root);
        for(int i = 1; i < list.size(); i++){
            if(list.get(i) <= list.get(i-1)){
                return false;
            }
        }
        return true;
    }

    private void dfs(TreeNode root){
        if(root == null){
            return;
        }
        dfs(root.left);
        list.add(root.val);
        dfs(root.right);
    }
}

第二种方法,直接用递归进行检查。注意我们要用Long.MAX_VALUE和Long.MIN_VALUE来输出最大和最小值,否则会被测试用例的边界值卡死。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

    public boolean isValidBST(TreeNode root) {
        return dfs(root,Long.MIN_VALUE,Long.MAX_VALUE);
    }

    private boolean dfs(TreeNode root, long min, long max){
        if(root == null){
            return true;
        }
        if(root.val <= min || root.val >= max){
            return false;
        }
        return dfs(root.left,min,root.val) && dfs(root.right, root.val, max);
    }
}

 

LeetCode 98

标签:递归   arch   false   检查   get   http   arc   方法   存在   

原文地址:https://www.cnblogs.com/ZJPaang/p/12829608.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!