BST

99. Recover Binary Search Tree

  1. x, y are nodes to swap, pre is previous node

Iterative

def recoverTree(self, root: TreeNode) -> None:
    x = y = pre = None
    stack = []
    node = root
    
    while stack or node:
        while node:
            stack.append(node)
            node = node.left
        node = stack.pop()
        
         # 先遇到 x or y, pre代表的點不一樣
        if pre and pre.val > node.val:
            y = node
            if x == None:
                x = pre
            else:
                break
        pre = node
        node = node.right
            
    x.val, y.val = y.val, x.val

Recursive

Morris

450 Delete Node

  • 1 child, 2 child situation

  • 2 child => find min in right child

  • delete min in right child

701 Insert Node in BST

  • construct the node when root == null, otherwise just pass the node

98 valid BST

  • 不能直接跟root.left, root.right比

  • 利用dfs設定邊界

173 BST Iterator

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.

Calling next() will return the next smallest number in the BST.

Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.

  • Use a stack to store next smallest number

  • apply addLeft method, add left nodes to stack

285 Inorder successor in BST

Given a binary search tree and a node in it, find the in-order successor of that node in the BST.

Note: If the given node has no in-order successor in the tree, return null.

510 Inorder Successor in BST II

Given a node in a binary search tree, find the in-order successor of that node in the BST. If that node has no in-order successor, return null. The Node has parent attribute

Search Range

  • Recursion - create helper

firstGreaterThanK

  • if node.data > k, record current node (no right tree on node.left)

230 find Kth smallest element in BST

  • inorder

315. Count of Smaller Numbers After Self

You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].

Last updated

Was this helpful?