Binary Search Tree

Tree 的一种,比较特殊。

技巧

1。左子树的值 < 当前节点 < 右子树的值。

2。中序遍历(Inorder Traversal)会返回递增序列。

3。做DFS的时候,一般需要给定 minmax ,即当前节点的取值范围。

e.g. Unique Binary Search Trees II

经典题目

285 Inorder Successor in BST

def inorderSuccessor(self, root, p):
    """
    :type root: TreeNode
    :type p: TreeNode
    :rtype: TreeNode
    """
    if p.right is not None:
        return self.leftmost(p.right)
    else:
        return self.firstLarger(root, p)

def firstLarger(self, root, p):
    ans = None
    while root is not None:
        if root.val > p.val:
            ans = root
            root = root.left
        else:
            root = root.right
    return ans

def leftmost(self, node):
    while node.left is not None:
        node = node.left
    return node

95 Unique Binary Search Trees II

BST Sequences (CC189)

Rank from Stream (CC189)

Imagine you are reading in a stream of integers. Periodically, you wish to be able to loop up the rank of a number x (the number of values less than or equal to x). Implement the data structures and algorithms to support these operations. That is, implement the method track(int x), which is called when each number is generated, and the method getRankOfNumber(int x), which returns the number of values less than or equal to x (not including x itself).

Last updated