Accepted Java solution


  • 12
    V

    import java.util.Stack;

    public class Solution {

    Stack<Integer> stack = new Stack<Integer>();

    public void inOrder(TreeNode root){

    if(root != null){
        inOrder(root.left);
        stack.push(root.val);
        inOrder(root.right);
    }
    

    }
    public boolean isValidBST(TreeNode root){

    if(root == null){
        return true;
    }
    
    inOrder(root);
    int i = stack.pop();
    
    while(!stack.isEmpty()){
        int j = stack.pop();
        if(i <= j){
            return false;
        }
        i = j;
    }
    
    return true;
    

    }
    }


  • 0
    L

    Really a good and natural solution ! Thanks.


  • 0
    M

    maybe we should force convert like this:
    int i = (int)stack.pop();


  • 0
    U

    nice solution!


  • 0
    R

    nice idea of utilizing the fact that they will be sorted if traversed inorder.


Log in to reply
 

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