1902. Depth of BST Given Insertion Order

Updated: 2024-03-12
1 min read
[]

On This Page

LeetCode problem 1902

from sortedcontainers import SortedDict


class Solution:
    def maxDepthBST(self, order: List[int]) -> int:
        sd = SortedDict({0: 0, inf: 0, order[0]: 1})
        res = 1
        for v in order[1:]:
            lower = sd.bisect_left(v) - 1
            higher = lower + 1
            depth = 1 + max(sd.values()[lower], sd.values()[higher])
            res = max(res, depth)
            sd[v] = depth
        return res