Simple Java - Inorder traversal, a stack to track the immediate prior node/number.


  • 2
    J
    public boolean isValidBST(TreeNode root) {
    	Stack<Integer> prev = new Stack<>();
    	return inorder(root, prev);
    }
    
    private boolean inorder(TreeNode node, Stack<Integer> prev) {
    	if (node == null) return true;
    	if (!inorder(node.left, prev)) return false;
    	if (!prev.isEmpty() && prev.pop() >= node.val) return false;
    	prev.push(node.val);
    	return inorder(node.right, prev);
    }

Log in to reply
 

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