• + 0 comments

    My Python 3 code with a customized binary search tree. Passed all the tess. I know in the worst case, this is O(n^2). But in most cases, it is like O(n log n), if the tree is somewhat balanced.

    class Node: def init(self, key): self.left = None self.right = None self.val = key

    def minimumLoss(price): # Write your code here

    min_loss = float('inf')
    
    root = Node(price[0])
    prev = root
    
    for p in price:
    
        current = root
    
        while True:
    
            if current is None:
                if p > prev.val:
                    prev.right = Node(p)
                    break
                elif p < prev.val:
                    prev.left = Node(p)
                    break
            elif current.val == p:
                break
            elif current.val < p:
                prev = current
                current = current.right
            elif current.val > p:
                prev = current
                min_loss = min(min_loss, current.val - p)
                                                current = current.left
    
    return min_loss