Simple answer questions.
(a) Given the array of integers arr shown below (3 分)
4 | 8 | 10 | 36 | 48 | 60 | 20 | 30 | 21 | 19
What is the output of the following statements?
int[] a2 = arr; a2[3] = arr[2]; arr[2] = arr[3]; arr[3] = a2[3]; System.out.println(arr[2] + " " + arr[3]);
(b) If a binary search tree is not allowed to have duplicates, there is more than one way to delete a node in the tree when that node has two children. One way involves choosing a replacement node from the left subtree. Please explain how to find the replacement node from the left subtree. (3 分)
(a) a2 = arr 是同一個陣列的別名,改 a2 就是改 arr
a2[3] = arr[2] → arr[3] = 10
arr[2] = arr[3] → arr[2] = 10
arr[3] = a2[3] → arr[3] = 10
10 10
(b) replacement = 左子樹中最大的節點(inorder predecessor)
① 走到被刪節點的左子節點 ② 一直往右子節點走,直到沒有右子節點 ③ 停下的節點就是 replacement
把它的 key 複製到被刪節點,再刪掉這個 replacement 節點(它沒有右子,最多一個左子,用左子接上它的位置)
這個值比左子樹其他節點都大、又比右子樹所有節點小,換上去後 BST 性質不變