what's wrong with the judgement code in python?why this solution cannot pass ac?


  • 0
    B
    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def isValidBST(self, root):
            """
            :type root: TreeNode
            :rtype: bool
            """
            stack = []
            pre = None
            while not stack or not root:
                while not root:
                    stack.append(root)
                    root = root.left
                root = stack.pop()
                if not pre and pre.val >= root.val:
                    return False
                pre = root
                root = root.right
            return True
                
    

    can not pass ac. it throws Line 20: IndexError: pop from empty list.
    while i change it to the following code, it accepted!

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def isValidBST(self, root):
            """
            :type root: TreeNode
            :rtype: bool
            """
            stack = []
            pre = None
            while len(stack) != 0 or root != None:
                while root != None:
                    stack.append(root)
                    root = root.left
                root = stack.pop()
                if pre != None and pre.val >= root.val:
                    return False
                pre = root
                root = root.right
            return True
    

Log in to reply
 

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