Accepted Java solution, don't need to traverse the whole tree


  • 0
    M
    public boolean isValidBST(TreeNode root) {
        List<Integer> list=new ArrayList<>();
        return traverse(list,root);
        
    }
    public boolean traverse(List<Integer> list, TreeNode node){
        if(node==null){
            return true;
        }
        boolean valid=true;
        valid=valid && traverse(list,node.left);
        if(list.size()==0 || node.val>list.get(list.size()-1)){
            list.add(node.val);
        }
        else{
            return false;
        }
        valid=valid && traverse(list,node.right);
        return valid;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.