Is This a Binary Search Tree?

  • + 0 comments

    My original solution is:

    def inOrder(root, stack=[]):
        if root.left:
            inOrder(root.left, stack)
        stack.append(root.data)
        if root.right:
            inOrder(root.right, stack)
    
            
    def check_binary_search_tree_(root):
        stack = []
        inOrder(root, stack)
        length = len(stack)
        for i in range(length-1):
            if stack[i] >= stack[i+1]:
                return False
        return True
    

    With your comment, I coded the following solution in python3:

    flag = True
    pre = -1  # As all data are >= 0 so set pre = -1
    
    
    def inOrder(root):
        global flag, pre
        if root.left:
            inOrder(root.left)
        if pre < root.data:
            pre = root.data
        else:
            flag = False
            return
        if root.right:
            inOrder(root.right)
    
    
    def check_binary_search_tree_(root):
        inOrder(root)
        global flag
        return flag