You are on page 1of 8

資料結構助教課

2019/12/02
2

Successor and Predecessor


• Assuming that all keys are distinct,
– y=successor[x]  key[y] is the smallest key > key[x]
– y=predecessor[x]  key[y] is the largest key < key[x]
• We can find x’s successor based entirely on the tree structure. No key
comparisons are necessary
• If x has the largest key in the binary search tree, then we say that x’s s
uccessor is NIL
To identify y, the successor of x, there are two cases:
1. If node x has a non-empty right subtree, then y is the minimum in x’s ri
ght subtree (i.e. the leftmost node in the right subtree)
2. If node x has an empty right subtree,
– x must NOT be in y’s right subtree, and be the maximum in y’s left s
ubtree
– y is the lowest ancestor of x whose left child is also an ancestor of x
– i.e. if we move up from x, y is the first ancestor we encounter when
we go right

NCKU IIM 資料結構 Chapter 12


3

Searching for Successor


y=successor[x]
Key points: y>x
y
– y is in x’s right subtree (y1: the minimum in x’s right subtree)
y
– x is in y’s left subtree (y2 : the lowest such ancestor)
x – y1< y2  first check the existence of y1, then y2
y

y=predecessor[x]
Key points: y<x
y
– y is in x’s left subtree (y1: the maximum in x’s left subtree)
y – x is in y’s right subtree (y2 : the maximum in x’s ancestors)
x
– y1< y2  first check the existence of y1, then y2
y

NCKU IIM 資料結構 Chapter 12


4

Searching for Successor


TREE-SUCCESSOR(x)
if right[x] ≠ NIL
then return TREE-MINIMUM(right[x])
y ← p[x]
while y ≠ NIL and x = right[y]
do x ← y
y ← p[y]
return y
Q: the successor of the node with key value 15,6,4,17=? A: 17,7,6,18
Q: the predecessor of the node with key value 15,6,4,17=? A: 13,4,3,15
• TREE-PREDECESSOR is symmetric to TREE-SUCCESSOR
i.e. change right[x] by left[x] & TREE-MAXIMUM by TREE-MINIMUM
Time: O(h) y y
y y
y=successor[x] x y=predessor[x] x

y y

NCKU IIM 資料結構 Chapter 12


Bucket Sort

• Assume the input is drawn from a uniform distribution,


say, between [0,1)
BUCKET-SORT(A,n)
for i=1 to n
insert A[i] into list B[floor(nA[i])]
for i=0 to n-1
sort B[i] with insertion sort
concatenate the lists B[0], B[1],…,B[n-1] together in order

• Practice
• Assume the input is drawn from a uniform distribution,
say, between [a,b)
5
Answer

• Assume the input is drawn from a uniform distribution,


say, between [a,b)

BUCKET-SORT(A,n)
for i=1 to n
insert A[i] into list B[floor(n*( A[i]-a ) / (b-a) )]
for i=0 to n-1
sort B[i] with insertion sort
concatenate the lists B[0], B[1],…,B[n-1] together in order

6
Batch code 例子

• mean.exe
• 計算陣列的平均值
• Input: [n, min, max, rs]
• Output: the mean of array
• run_all.bat
1. 建立一個輸入檔 input.txt
2. feed 這個輸入檔 input.txt 給執行檔 mean.exe
3. 將結果輸出到 output.txt

• 練習寫出一個 batch ,執行 mean.exe 兩次, input 分別為 [100,1,


200,1] 及 [1000,1,2000,2] 。
run_all.bat

You might also like