My accepted Java solution using stack

  • 1

    import java.util.Stack;

    public class Solution {

    Stack<Integer> stack = new Stack<Integer>();
    public void inOrder(TreeNode root){
    	if(root != null){
    public boolean isValidBST(TreeNode root){
        if(root == null){
            return true;
    	int i = stack.pop();
    		int j = stack.pop();
    		if(i <= j){
    			return false;
    		i = j;
    	return true;


    The basic idea is that, first store all values of this tree in-order, from left to parent to right.

    Then if the tree is a binary search tree, values in stack should from maximum to minimum, so we pop each element one by one and compare these elements one by one.

    If a new popped element is greater than the previous one, we can conclude that this isn't a BST.

Log in to reply

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