Introduction to Algorithms (Binary Search Trees, BST Sort)

 Runway Reservation System

  • Airport with single runway
  • Reservations for future landings
  • Reserve request specifies landing time t
  • Add t to the set R if no other landings are scheduled within k minutes
  • Remove from set R after plane lands

Algorithm (Keep R as a sorted list)

init: R = [ ]
req(t): if t < now: return "error"
for i in range (len(R)):
if abs(t-R[i]) < k: return "error"
R.append(t)
R = sorted(R)
land: t = R[0]
if (t != now) return error
R = R[1: ] (drop R[0] from R)

Can we do better? 

  • Sorted list: Appending and sorting takes Θ(n lg n) time. However, it is possible to insert new time/plane rather than append and sort but insertion takes Θ(n) time. A k minute check can be done in O(1) once the insertion point is found.
  • Sorted array: It is possible to do binary search to find place to insert in O(lg n) time. Using binary search, we find the smallest i such that R[i] ≥ t, i.e., the next larger element. We then compare R[i] and R[i − 1] against t. Actual insertion however requires shifting elements which requires Θ(n) time.
  • Unsorted list/array: k minute check takes O(n) time.
  • Min-Heap: It is possible to insert in O(lg n) time. However, the k minute check will require O(n) time.
  • Dictionary or Python Set: Insertion is O(1) time. k minute check takes Ω(n) time

BST

Properties

Each node x in the binary tree has a key key(x). Nodes other than the root have a parent p(x). Nodes may have a left child lef t(x) and/or a right child right(x). These are pointers unlike in a heap.

The invariant is: for any node x, for all nodes y in the left subtree of x, key(y) ≤ key(x). For all nodes y in the right subtree of x, key(y) ≥ key(x).

Operations:

  • insert(x)
  • find_min()
  • next_larger(x)
next_larger(x):

    if right child not nil, return minimum(right)
    else y = parent(x)
    
    while y not nil and x = right(y)
        x = y;
        y = parent(y)

    return y
  • rank(t): How many planes are scheduled to land at times ≤ t? The new requirement necessitates a design amendment.
1. walk down the tree to find desired time
2. Add in the nodes that are smaller
3. Add in the subtrees size to the left

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值