leetcode 98. Validate Binary Search Tree

孤街浪徒 提交于 2019-11-27 11:25:50

按题意检查即可

可以递归,会比较好理解,逐渐收缩max和min

class Solution {
    public boolean isValidBST(TreeNode root) {
        return helper(root, Long.MAX_VALUE, Long.MIN_VALUE);
        
    }
    private boolean helper(TreeNode root , long max, long min){
        if(root == null)
            return true;
        if(root.val >= max || root.val <= min)
            return false;
        
        return helper(root.left, root.val, min) && helper(root.right, max, root.val);
    }
    

}

也可以迭代,利用中序遍历

class Solution {
    public boolean isValidBST(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        if(root == null)
            return true;
        TreeNode pre = null;
        
        while(root != null || !stack.isEmpty()){
            while(root!= null){
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if(pre != null && root.val <= pre.val)
                return false;
            pre = root;
            root = root.right;
        }
        return true;
        
    }
    

}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!