My solution based on inorder traversal


  • 0
    R

    Each iteration will push the new val on the top of the stack

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
     // inorder traversal
    public class Solution {
        public boolean isValidBST(TreeNode root) {
        Stack<Integer> st = new Stack<Integer>();
        return inorderT(root, st);
        }
        public boolean inorderT(TreeNode root, Stack<Integer> st) {
            if( root == null ) return true;
            if(inorderT(root.left, st) == false) return false;
            if(st.isEmpty()) st.push(root.val);
            else{ 
                if(st.peek() >= root.val)
                    return false;
                else{
                    st.push(root.val);
                }
            }
            if(inorderT(root.right, st) == false) return false;
            return true;
        }
    }
    

Log in to reply
 

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