Non-recursive using python


  • 0
    B
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if root is None:
            return True
        stack = [root]
        root.left_parent = None
        root.right_parent = None
        while stack:
            node = stack.pop()
            if node.left:
                if node.left.val >= node.val:
                    return False
                if node.right_parent and node.left.val <= node.right_parent:
                    return False
                node.left.left_parent = node.val
                node.left.right_parent = node.right_parent
                stack.append(node.left)
            if node.right:
                if node.right.val <= node.val:
                    return False
                if node.left_parent and node.right.val >= node.left_parent:
                    return False
                node.right.right_parent = node.val
                node.right.left_parent = node.left_parent
                stack.append(node.right)
        
        return True

Log in to reply
 

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