Python inorder non-recursive solution, using stack

  • 4
    class Solution(object):
        def isValidBST(self, root):
            :type root: TreeNode
            :rtype: bool
            # using inorder - binary search tree will be ascending order
            stack = []
            cur = root
            pre = None
            while len(stack) or cur:
                if cur:
                    cur = cur.left
                    p = stack.pop()
                    if pre and p.val <= pre.val:
                        return False
                    pre = p
                    cur = p.right
            return True

Log in to reply

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