You are on page 1of 50

Đã bắt đầu vào Thứ bảy, 28 Tháng mười 2023, 12:38 PM

lúc
Tình trạng Đã hoàn thành
Hoàn thành vào Thứ bảy, 28 Tháng mười 2023, 4:23 PM
lúc
Thời gian thực 3 giờ 44 phút
hiện
Điểm 17,00/17,00
Điểm 10,00 của 10,00 (100%)
Câu hỏi 1
Chính xác

Điểm 1,00 của 1,00

Implement static methods Partition and QuickSort in class Sorting to sort an array in ascending order.

#ifndef SORTING_H
#define SORTING_H
#include <sstream>
#include <iostream>
#include <type_traits>
using namespace std;
template <class T>
class Sorting {
private:
static T* Partition(T* start, T* end) ;
public:
static void QuickSort(T* start, T* end) ;
};
#endif /* SORTING_H */

You can read the pseudocode of the algorithm used to in method Partition in the below image.

For example:

Test Result

int array[] = { 3, 5, 7, 10 ,12, 14, 15, 13, 1, 2, 9, 6, 4, 8, 11, 16, Index of pivots: 2 0 0 6 1 0 2 1 0 0 2 1 0 0 0 0 0 0
17, 18, 20, 19 }; 1 0
cout << "Index of pivots: "; Array after sorting: 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Sorting<int>::QuickSort(&array[0], &array[20]); 15 16 17 18 19 20
cout << "\n";
cout << "Array after sorting: ";
for (int i : array) cout << i << " ";

Answer: (penalty regime: 0 %)

Reset answer

1 ▼ static T* Partition(T* start, T* end) {


2 // TODO: return the pointer which points to the pivot after rearrange the array.
3 int L = end - start;
4
5 T pivot = start[0];
6 int left = 1;
7 int right = L - 1;
8 while (true)
9 ▼ {
10 while (left <= right && start[left] < pivot)
11 ++left;
12
13 while (right >= left && pivot < start[right])
14 --right;
15
16 if (left >= right)
17 break;
18
19 swap(start[left], start[right]);
20 ++left;
21 --right;
22 }
23
24 swap(start[0], start[right]);
25 cout<< right << " ";
26
27 return start + right;
28 }
29
30 ▼ static void QuickSort(T* start, T* end) {
31 if(start < end)
32 ▼ {
33 T *pi = Partition(start, end);
34 QuickSort(start, pi);
35 QuickSort(pi + 1, end);
36 }
37 }

Test Expected Got

 int array[] = { 3, 5, 7, 10 ,12, 14, 15, 13, 1, 2, Index of pivots: 2 0 0 6 1 0 2 Index of pivots: 2 0 0 6 1 0 
9, 6, 4, 8, 11, 16, 17, 18, 20, 19 }; 1 0 0 2 1 0 0 0 0 0 0 1 0 2 1 0 0 2 1 0 0 0 0 0 0 1 0
cout << "Index of pivots: "; Array after sorting: 1 2 3 4 5 Array after sorting: 1 2 3 4
Sorting<int>::QuickSort(&array[0], &array[20]); 6 7 8 9 10 11 12 13 14 15 16 5 6 7 8 9 10 11 12 13 14 15
cout << "\n"; 17 18 19 20 16 17 18 19 20
cout << "Array after sorting: ";
for (int i : array) cout << i << " ";

Passed all tests! 

Chính xác
Điểm cho bài nộp này: 1,00/1,00.
Câu hỏi 2
Chính xác

Điểm 1,00 của 1,00

The best way to sort a singly linked list given the head pointer is probably using merge sort.

Both Merge sort and Insertion sort can be used for linked lists. The slow random-access performance of a linked list makes other algorithms
(such as quick sort) perform poorly, and others (such as heap sort) completely impossible. Since worst case time complexity of Merge Sort is
O(nLogn) and Insertion sort is O(n^2), merge sort is preferred.

Additionally, Merge Sort for linked list only requires a small constant amount of auxiliary storage.

To gain a deeper understanding about Merge sort on linked lists, let's implement mergeLists and mergeSortList function below
Constraints:

0 <= list.length <= 10^4


0 <= node.val <= 10^6
Use the nodes in the original list and don't modify ListNode's val attribute.

struct ListNode {
int val;
ListNode* next;
ListNode(int _val = 0, ListNode* _next = nullptr) : val(_val), next(_next) { }
};

// Merge two sorted lists


ListNode* mergeSortList(ListNode* head);

// Sort an unsorted list given its head pointer


ListNode* mergeSortList(ListNode* head);

For example:

Test Input Result

int arr1[] = {1, 3, 5, 7, 9}; 1 2 3 4 5 6 7 8 9


int arr2[] = {2, 4, 6, 8};
unordered_map<ListNode*, int> nodeAddr;
ListNode* a = init(arr1, sizeof(arr1) / 4, nodeAddr);
ListNode* b = init(arr2, sizeof(arr2) / 4, nodeAddr);
ListNode* merged = mergeLists(a, b);
try {
printList(merged, nodeAddr);
}
catch(char const* err) {
cout << err << '\n';
}
freeMem(merged);
Test Input Result

int size; 9 1 2 3 4 5 6 7 8 9
cin >> size; 9 3 8 2 1 6 7 4 5
int* array = new int[size];
for(int i = 0; i < size; i++) cin >> array[i];
unordered_map<ListNode*, int> nodeAddr;
ListNode* head = init(array, size, nodeAddr);
ListNode* sorted = mergeSortList(head);
try {
printList(sorted, nodeAddr);
}
catch(char const* err) {
cout << err << '\n';
}
freeMem(sorted);
delete[] array;

Answer: (penalty regime: 0 %)

Reset answer
4
5▼ while (a != nullptr && b != nullptr) {
6▼ if (a->val <= b->val) {
7 *mergedTail = a;
8 mergedTail = &(a->next);
9 a = a->next;
10 ▼ } else {
11 *mergedTail = b;
12 mergedTail = &(b->next);
13 b = b->next;
14 }
15 }
16
17 *mergedTail = (a != nullptr) ? a : b;
18
19 return mergedHead;
20 }
21
22 ▼ ListNode* mergeSortList(ListNode* head) {
23 ▼ if (head == nullptr || head->next == nullptr) {
24 return head;
25 }
26
27 ListNode* slow = head;
28 ListNode* fast = head->next;
29
30 ▼ while (fast != nullptr && fast->next != nullptr) {
31 slow = slow->next;
32 fast = fast->next->next;
33 }
34
35 ListNode* secondHalf = slow->next;
36 slow->next = nullptr;
37
38 ListNode* sortedFirstHalf = mergeSortList(head);
39 ListNode* sortedSecondHalf = mergeSortList(secondHalf);
40
41 return mergeLists(sortedFirstHalf, sortedSecondHalf);
42 }
43
Test Input Expected Got

 int arr1[] = {1, 3, 5, 7, 9}; 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 


int arr2[] = {2, 4, 6, 8};
unordered_map<ListNode*, int> nodeAddr;
ListNode* a = init(arr1, sizeof(arr1) / 4, nodeAddr);
ListNode* b = init(arr2, sizeof(arr2) / 4, nodeAddr);
ListNode* merged = mergeLists(a, b);
try {
printList(merged, nodeAddr);
}
catch(char const* err) {
cout << err << '\n';
}
freeMem(merged);

 int size; 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 
cin >> size; 9 3 8 2 1 6 7 4 5
int* array = new int[size];
for(int i = 0; i < size; i++) cin >> array[i];
unordered_map<ListNode*, int> nodeAddr;
ListNode* head = init(array, size, nodeAddr);
ListNode* sorted = mergeSortList(head);
try {
printList(sorted, nodeAddr);
}
catch(char const* err) {
cout << err << '\n';
}
freeMem(sorted);
delete[] array;

Passed all tests! 

Chính xác
Điểm cho bài nộp này: 1,00/1,00.
Câu hỏi 3
Chính xác

Điểm 1,00 của 1,00

Implement static methods merge, InsertionSort and TimSort in class Sorting to sort an array in ascending order.

merge is responsible for merging two sorted subarrays. It takes three pointers: start, middle, and end, representing the left, middle, and right
portions of an array.

InsertionSort is an implementation of the insertion sort algorithm. It takes two pointers, start and end, and sorts the elements in the range
between them in ascending order using the insertion sort technique.

TimSort is an implementation of the TimSort algorithm, a hybrid sorting algorithm that combines insertion sort and merge sort. It takes two
pointers, start and end, and an integer min_size, which determines the minimum size of subarrays to be sorted using insertion sort. The
function first applies insertion sort to small subarrays, prints the intermediate result, and then performs merge operations to combine sorted
subarrays until the entire array is sorted.

#ifndef SORTING_H
#define SORTING_H
#include <sstream>
#include <iostream>
#include <type_traits>
using namespace std;
template <class T>
class Sorting {
private:
static void printArray(T* start, T* end)
{
int size = end - start;
for (int i = 0; i < size - 1; i++)
cout << start[i] << " ";
cout << start[size - 1];
cout << endl;
}

static void merge(T* start, T* middle, T* end) ;


public:
static void InsertionSort(T* start, T* end) ;
static void TimSort(T* start, T* end, int min_size) ;
};
#endif /* SORTING_H */

For example:
Test Result

int array[] = { 19, 20, 18, 17 ,12, 13, 14, 15, 1, 2, 9, 6, 4, 7, 11, 16, Insertion Sort: 17 18 19 20 12 13 14 15 1 2 6 9 4 7
10, 8, 5, 3 }; 11 16 3 5 8 10
int min_size = 4; Merge 1: 12 13 14 15 17 18 19 20 1 2 6 9 4 7 11 16 3
Sorting<int>::TimSort(&array[0], &array[20], min_size); 5 8 10
Merge 2: 12 13 14 15 17 18 19 20 1 2 4 6 7 9 11 16 3
5 8 10
Merge 3: 12 13 14 15 17 18 19 20 1 2 4 6 7 9 11 16 3
5 8 10
Merge 4: 1 2 4 6 7 9 11 12 13 14 15 16 17 18 19 20 3
5 8 10
Merge 5: 1 2 4 6 7 9 11 12 13 14 15 16 17 18 19 20 3
5 8 10
Merge 6: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
18 19 20

int array[] = { 3, 20, 18, 17 ,12, 13, 14, 15, 1, 2, 9, 6, 4, 7, 11, 16, Insertion Sort: 3 17 18 20 12 13 14 15 1 2 6 9 4 7
10, 8, 5, 19 }; 11 16 5 8 10 19
int min_size = 4; Merge 1: 3 12 13 14 15 17 18 20 1 2 6 9 4 7 11 16 5
Sorting<int>::TimSort(&array[0], &array[20], min_size); 8 10 19
Merge 2: 3 12 13 14 15 17 18 20 1 2 4 6 7 9 11 16 5
8 10 19
Merge 3: 3 12 13 14 15 17 18 20 1 2 4 6 7 9 11 16 5
8 10 19
Merge 4: 1 2 3 4 6 7 9 11 12 13 14 15 16 17 18 20 5
8 10 19
Merge 5: 1 2 3 4 6 7 9 11 12 13 14 15 16 17 18 20 5
8 10 19
Merge 6: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
18 19 20

Answer: (penalty regime: 0 %)

Reset answer

1 ▼ static void merge(T* start, T* middle, T* end) {


2 // TODO
3 int size1 = middle - start + 1;
4 int size2 = end - middle;
5 int i1 = 0, i2 = 0, k = 0;
6 int* l = new int[size1];
7 int* r = new int[size2];
8 ▼ for(int i = 0; i < size1; i++){
9 l[i] = start[i];
10 }
11 ▼ for(int j = 0; j <size2; j++){
12 r[j] = middle[j+1];
13 }
14 ▼ while(i1<size1 && i2 < size2){
15 ▼ if(l[i1] <= r[i2]){
16 start[k++] = l[i1++];
17 }
18 ▼ else{
19 start[k++] = r[i2++];
20 }
21 }
22 ▼ while(i1<size1){
23 start[k++] = l[i1++];
24 }
25 ▼ while(i1<size2){
26 start[k++] = r[i2++];
27 }
28 }
29
30 ▼ static void InsertionSort(T* start, T* end) {
31 // TODO
32 int n = end - start;
33 ▼ for(int i = 1; i<n;i++){
f (i j i j && [j] [j ] j ){
34 ▼ for(int j = i; j>0 && start[j] < start[j-1]; j--){
35 swap(start[j],start[j-1]);
36 }
37 }
38 }
39
40 ▼ static void TimSort(T* start, T* end, int min_size) {
41 // TODO
42 // You must print out the array after using insertion sort and everytime calling method merge.
43 int n = end - start;
44 T*s = start, *e=end;
45 ▼ for(int i = 0; i < n; i+=min_size){
46 ▼ if(i+min_size<=n){
47 InsertionSort(s,s+min_size);
48 s += min_size;
49 }
50 else InsertionSort(s,e);
51 }
52 cout << "Insertion Sort: ";
53 printArray(start,end);
54 int count = 0;
55 ▼ for (int gap = min_size; gap < n; gap*=2){
56 s = start;
57 ▼ for (int j = 0; j < n; j+=2*gap){
58 T* mid = s + gap - 1;
59 if (j + gap - 1 >= n) mid = end - 1;
60 if (j + 2 * gap - 1 < n)
61 e = s + 2 * gap - 1;
62 else e = end - 1;
63 merge(s, mid, e);
64 cout << "Merge " << ++count << ": ";
65 printArray(start,end);
66 s += 2 * gap;
67 }
68 }
69 }
Test Expected Got

 int array[] = { 19, 20, 18, 17 ,12, 13, 14, 15, 1, Insertion Sort: 17 18 19 20 12 Insertion Sort: 17 18 19 20 12 
2, 9, 6, 4, 7, 11, 16, 10, 8, 5, 3 }; 13 14 15 1 2 6 9 4 7 11 16 3 5 13 14 15 1 2 6 9 4 7 11 16 3 5
int min_size = 4; 8 10 8 10
Sorting<int>::TimSort(&array[0], &array[20], Merge 1: 12 13 14 15 17 18 19 Merge 1: 12 13 14 15 17 18 19
min_size); 20 1 2 6 9 4 7 11 16 3 5 8 10 20 1 2 6 9 4 7 11 16 3 5 8 10
Merge 2: 12 13 14 15 17 18 19 Merge 2: 12 13 14 15 17 18 19
20 1 2 4 6 7 9 11 16 3 5 8 10 20 1 2 4 6 7 9 11 16 3 5 8 10
Merge 3: 12 13 14 15 17 18 19 Merge 3: 12 13 14 15 17 18 19
20 1 2 4 6 7 9 11 16 3 5 8 10 20 1 2 4 6 7 9 11 16 3 5 8 10
Merge 4: 1 2 4 6 7 9 11 12 13 Merge 4: 1 2 4 6 7 9 11 12 13
14 15 16 17 18 19 20 3 5 8 10 14 15 16 17 18 19 20 3 5 8 10
Merge 5: 1 2 4 6 7 9 11 12 13 Merge 5: 1 2 4 6 7 9 11 12 13
14 15 16 17 18 19 20 3 5 8 10 14 15 16 17 18 19 20 3 5 8 10
Merge 6: 1 2 3 4 5 6 7 8 9 10 Merge 6: 1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20 11 12 13 14 15 16 17 18 19 20

 int array[] = { 3, 20, 18, 17 ,12, 13, 14, 15, 1, 2, Insertion Sort: 3 17 18 20 12 Insertion Sort: 3 17 18 20 12 
9, 6, 4, 7, 11, 16, 10, 8, 5, 19 }; 13 14 15 1 2 6 9 4 7 11 16 5 8 13 14 15 1 2 6 9 4 7 11 16 5 8
int min_size = 4; 10 19 10 19
Sorting<int>::TimSort(&array[0], &array[20], Merge 1: 3 12 13 14 15 17 18 Merge 1: 3 12 13 14 15 17 18
min_size); 20 1 2 6 9 4 7 11 16 5 8 10 19 20 1 2 6 9 4 7 11 16 5 8 10 19
Merge 2: 3 12 13 14 15 17 18 Merge 2: 3 12 13 14 15 17 18
20 1 2 4 6 7 9 11 16 5 8 10 19 20 1 2 4 6 7 9 11 16 5 8 10 19
Merge 3: 3 12 13 14 15 17 18 Merge 3: 3 12 13 14 15 17 18
20 1 2 4 6 7 9 11 16 5 8 10 19 20 1 2 4 6 7 9 11 16 5 8 10 19
Merge 4: 1 2 3 4 6 7 9 11 12 Merge 4: 1 2 3 4 6 7 9 11 12
13 14 15 16 17 18 20 5 8 10 19 13 14 15 16 17 18 20 5 8 10 19
Merge 5: 1 2 3 4 6 7 9 11 12 Merge 5: 1 2 3 4 6 7 9 11 12
13 14 15 16 17 18 20 5 8 10 19 13 14 15 16 17 18 20 5 8 10 19
Merge 6: 1 2 3 4 5 6 7 8 9 10 Merge 6: 1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20 11 12 13 14 15 16 17 18 19 20

Passed all tests! 

Chính xác
Điểm cho bài nộp này: 1,00/1,00.
Câu hỏi 4
Chính xác

Điểm 1,00 của 1,00

Given a list of distinct unsorted integers nums.

Your task is to implement a function with following prototype:


int minDiffPairs(int* arr, int n);
This function identify and return all pairs of elements with the smallest absolute difference among them. If there are multiple pairs that meet
this criterion, the function should find and return all of them.

Note: Following libraries are included: iostream, string, algorithm, sstream

For example:

Test Result

int arr[] = {10, 5, 7, 9, 15, 6, 11, 8, 12, 2}; (5, 6), (6, 7), (7, 8), (8, 9), (9, 10), (10, 11), (11, 12)
cout << minDiffPairs(arr, 10);

int arr[] = {10};


cout << minDiffPairs(arr, 1);

int arr[] = {10, -1, -150, 200}; (-1, 10)


cout << minDiffPairs(arr, 4);

Answer: (penalty regime: 0 %)

Reset answer

23
24 for (int i = 2; i < n; i++)
25 if (arr[i] - arr[i - 1] < minDiff)
26 minDiff = arr[i] - arr[i - 1];
27
28 for (int i = 0; i < n - 1; i++)
29 if (arr[i + 1] - arr[i] == minDiff)
30 count++;
31
32 for (int i = 0; i < n - 1; i++)
33 ▼ {
34 if (arr[i + 1] - arr[i] == minDiff)
35 ▼ {
36 count--;
37 result = result + "(" + to_string(arr[i]) + ", " + to_string(arr[i + 1]) + ")" + (count > 0 ? ", "
38
39 }
40 }
41
42 return result;
43
 

Test Expected Got 

 int arr[] = {10, 5, 7, 9, 15, 6, (5, 6), (6, 7), (7, 8), (8, 9), (9, (5, 6), (6, 7), (7, 8), (8, 9), (9, 
11, 8, 12, 2}; 10), (10, 11), (11, 12) 10), (10, 11), (11, 12)
cout << minDiffPairs(arr, 10);

 int arr[] = {10}; 


cout << minDiffPairs(arr, 1);

 int arr[] = {10, -1, -150, 200}; (-1, 10) (-1, 10) 
cout << minDiffPairs(arr, 4); 
Passed all tests! 

Chính xác
Điểm cho bài nộp này: 1,00/1,00.
Câu hỏi 5
Chính xác

Điểm 1,00 của 1,00

Print the elements of an array in the decreasing frequency order while preserving the relative order of the elements.

Students are not allowed to use map/unordered map.

iostream, algorithm libraries are included.

For example:

Test Result

int arr[] = {-4,1,2,2,-4,9,1,-1}; -4 -4 1 1 2 2 9 -1


int n = sizeof(arr) / sizeof(arr[0]);

sortByFrequency(arr, n);

for (int i = 0; i < n; i++)


cout << arr[i] << " ";

int arr[] = {-5,3,8,1,-9,-9}; -9 -9 -5 3 8 1


int n = sizeof(arr) / sizeof(arr[0]);

sortByFrequency(arr, n);

for (int i = 0; i < n; i++)


cout << arr[i] << " ";

Answer: (penalty regime: 0 %)

Reset answer

19 bool found = false;


20 ▼ for (auto& element : elements) {
21 ▼ if (element.value == arr[i]) {
22 element.frequency++;
23 found = true;
24 break;
25 }
26 }
27 ▼ if (!found) {
28 elements.push_back({arr[i], 1, i});
29 }
30 }
31
32 std::sort(elements.begin(), elements.end(), compareFrequency);
33
34 int index = 0;
35 ▼ for (const auto& element : elements) {
36 ▼ for (int i = 0; i < element.frequency; ++i) {
37 arr[index++] = element.value;
38 }
39 }
40 }
Test Expected Got

 \tint arr[] = {-4,1,2,2,-4,9,1,-1}; -4 -4 1 1 2 2 9 -1 -4 -4 1 1 2 2 9 -1 


\tint n = sizeof(arr) / sizeof(arr[0]);

\tsortByFrequency(arr, n);

\tfor (int i = 0; i < n; i++)


\t\tcout << arr[i] << " ";

 \tint arr[] = {-5,3,8,1,-9,-9}; -9 -9 -5 3 8 1 -9 -9 -5 3 8 1 


\tint n = sizeof(arr) / sizeof(arr[0]);

\tsortByFrequency(arr, n);

\tfor (int i = 0; i < n; i++)


\t\tcout << arr[i] << " ";

Passed all tests! 

Chính xác
Điểm cho bài nộp này: 1,00/1,00.
Câu hỏi 6
Chính xác

Điểm 1,00 của 1,00

Given a list of points on the 2-D plane (points[] with n elements) and an integer k. Your task in this exercise is to implement
the closestKPoints function to find K closest points to the given point (des_point) and print them by descending order of distances.
Prototype of closestKPoints:
void closestKPoints(Point points[], int n, Point& des_point, int k);

Note: The distance between two points on a plane is the Euclidean distance.
Template:
#include <iostream>
#include <string>
#include <cmath>
#include <vector>
#include <algorithm>

using namespace std;

class Point{
public:
int x, y;
Point(int x = 0, int y = 0){
this->x = x;
this->y = y;
}
void display(){
cout << "("<<x<<", "<<y<<")";
}
};

For example:

Test Result

Point points[] = {{3, 3},{5, -1},{-2, 4}}; (-2, 4)


int n = sizeof(points)/sizeof(points[0]); (3, 3)
int k = 2;
Point des_point = {0,2};
closestKPoints(points, n, des_point, k);

Point points[] = {{3, 3},{5, -1},{-2, 4}}; (-2, 4)


int n = sizeof(points)/sizeof(points[0]); (3, 3)
int k = 3; (5, -1)
Point des_point = {0,2};
closestKPoints(points, n, des_point, k);

Answer: (penalty regime: 0 %)

Reset answer

1 /* Your helping functions go here */


2 ▼ void closestKPoints(Point points[], int n, Point &des_point, int k){
3 //TODO
4
5 int i, j;
6 int max = 0;
7 Point tmp;
8
9 ▼ for (i = 1; i < n; i++) {
10 max = pow(points[i].x - des_point.x, 2) + pow(points[i].y - des_point.y, 2);
11 tmp = points[i];
12 j = i - 1;
13
14 ▼ while (j >= 0 && pow(points[j].x - des_point.x, 2) + pow(points[j].y - des_point.y, 2) > max) {
15 points[j + 1] = points[j];
16 j = j - 1;
17 }
18 points[j + 1] = tmp;
19 }
20 if(k > n) k = n;
21 ▼ for (int i = 0; i < k; i++) {
22 points[i].display();
23 cout << endl;
24 }
25 }
26

Test Expected Got

 Point points[] = {{3, 3},{5, -1},{-2, 4}}; (-2, 4) (-2, 4) 


int n = sizeof(points)/sizeof(points[0]); (3, 3) (3, 3)
int k = 2;
Point des_point = {0,2};
closestKPoints(points, n, des_point, k);

 Point points[] = {{3, 3},{5, -1},{-2, 4}}; (-2, 4) (-2, 4) 


int n = sizeof(points)/sizeof(points[0]); (3, 3) (3, 3)
int k = 3; (5, -1) (5, -1)
Point des_point = {0,2};
closestKPoints(points, n, des_point, k);

Passed all tests! 


Chính xác
Điểm cho bài nộp này: 1,00/1,00.
Câu hỏi 7
Chính xác

Điểm 1,00 của 1,00

Given a Binary tree, the task is to traverse all the nodes of the tree using Breadth First Search algorithm and print the order of visited nodes (has no
blank space at the end)
#include<iostream>
#include<string>
#include<queue>
using namespace std;

template<class K, class V>


class BinaryTree
{
public:
class Node;

private:
Node *root;

public:
BinaryTree() : root(nullptr) {}
~BinaryTree()
{
// You have to delete all Nodes in BinaryTree. However in this task, you can ignore it.
}

class Node
{
private:
K key;
V value;
Node *pLeft, *pRight;
friend class BinaryTree<K, V>;

public:
Node(K key, V value) : key(key), value(value), pLeft(NULL), pRight(NULL) {}
~Node() {}
};

void addNode(string posFromRoot, K key, V value)


{
if(posFromRoot == "")
{
this->root = new Node(key, value);
return;
}

Node* walker = this->root;


int l = posFromRoot.length();
for (int i = 0; i < l-1; i++)
{
if (!walker)
return;
if (posFromRoot[i] == 'L')
walker = walker->pLeft;
if (posFromRoot[i] == 'R')
walker = walker->pRight;
}
if(posFromRoot[l-1] == 'L')
walker->pLeft = new Node(key, value);
if(posFromRoot[l-1] == 'R')
walker->pRight = new Node(key, value);
}

// STUDENT ANSWER BEGIN


// STUDENT ANSWER END
};

You can define other functions to help you.


For example:

Test Result

BinaryTree<int, int> binaryTree; 4 6 9


binaryTree.addNode("",2, 4); // Add to root
binaryTree.addNode("L",3, 6); // Add to root's left node
binaryTree.addNode("R",5, 9); // Add to root's right node
binaryTree.BFS();

Answer: (penalty regime: 0 %)

Reset answer

1 // STUDENT ANSWER BEGIN


2 // You can define other functions here to help you.
3 void BFS()
4 ▼ {
5 Node *temp = root;
6 queue<Node *> q;
7 q.push(temp);
8 while (!q.empty())
9 ▼ {
10 temp = q.front();
11 q.pop();
12 cout << temp->value << " ";
13 if (temp->pLeft != NULL)
14 q.push(temp->pLeft);
15 if (temp->pRight != NULL)
16 q.push(temp->pRight);
17 }
18 }
19 // STUDENT ANSWER END
Test Expected Got

 BinaryTree<int, int> binaryTree; 4 6 9 4 6 9 


binaryTree.addNode("",2, 4); // Add to root
binaryTree.addNode("L",3, 6); // Add to root's left node
binaryTree.addNode("R",5, 9); // Add to root's right node
binaryTree.BFS();

Passed all tests! 

Chính xác
Điểm cho bài nộp này: 1,00/1,00.
Câu hỏi 8
Chính xác

Điểm 1,00 của 1,00

Class BTNode is used to store a node in binary tree, described on the following:

class BTNode {
public:
int val;
BTNode *left;
BTNode *right;
BTNode() {
this->left = this->right = NULL;
}
BTNode(int val) {
this->val = val;
this->left = this->right = NULL;
}
BTNode(int val, BTNode*& left, BTNode*& right) {
this->val = val;
this->left = left;
this->right = right;
}
};

Where val is the value of node (non-negative integer), left and right are the pointers to the left node and right node of it,
respectively.

Request: Implement function:

int longestPathSum(BTNode* root);


Where root is the root node of given binary tree (this tree has between 1 and 100000 elements). This function returns the sum
of the largest path from the root node to a leaf node. If there are more than one equally long paths, return the larger sum.

Example:

Given a binary tree in the following:

The longest path from the root node to the leaf node is 1-4-7-4-2, so return the sum of this path, is 18.

Explanation of function createTree: The function has three parameters. The first two parameters take in an array containing the
parent of each Node of the binary tree, and the third parameter takes in an array representing the respective values of the Nodes.
After processing, the function will construct the binary tree and return the address of the root Node. Note that the root Node is
designated with a parent value of -1.
Example:
int arr[] = {-1,0,0,2,2};
int value[] = {3,5,2,1,4};
BTNode* root = BTNode::createTree(arr, arr + sizeof(arr)/sizeof(int), value);
arr[0]=-1 means the Node containing the value value[0]=3 will be the root Node. Also, since arr[1]=arr[2]=0, it implies that the
Nodes containing the values value[1]=5 and value[2]=2 will have the Node containing the value value[0]=3 as their parent. Lastly,
since arr[3]=arr[4]=2, it means the Nodes containing the values value[3]=1 and value[4]=4 will have the Node with the
value value[2]=2 as their parent. Final tree of this example are shown in the figure above.
Note that whichever Node appears first in the arr sequence will be the left Node, and the TestCase always ensures that the
resulting tree is a binary tree.

Note: In this exercise, the libraries iostream, utility, queue, stack and using namespace std are used. You can write helper
functions; however, you are not allowed to use other libraries.

For example:

Test Result

int arr[] = {-1,0,0,2,2,3,3,5}; 18


int value[] = {1,5,4,7,12,4,8,2};
BTNode* root = BTNode::createTree(arr, arr + sizeof(arr)/sizeof(int), value);
cout << longestPathSum(root);

int arr[] = {-1,0,1,0,1,4,5,3,7,3}; 61


int value[] = {6,12,23,20,20,20,3,9,13,15};
BTNode* root = BTNode::createTree(arr, arr + sizeof(arr)/sizeof(int), value);
cout << longestPathSum(root);

Answer: (penalty regime: 0 %)

Reset answer

1 ▼ int longestPathSum(BTNode* root) {


2 ▼ if (! root){
3 return 0 ;
4 }
5 int maxLength = 0;
6 int maxSum = 0;
7 stack<pair<BTNode*,pair<int,int>>> stk;
8 stk.push({root, {1, root->val}});
9 ▼ while(!stk.empty()){
10 BTNode* current = stk.top().first;
11 int length = stk.top().second.first;
12 int sum = stk.top().second.second;
13 stk.pop();
14 ▼ if ( !current->left && !current->right){ // at the last node, the leaf one
15 ▼ if ( length > maxLength || (length == maxLength && sum > maxSum )){
16 maxLength = length;
17 maxSum = sum;
18 }
19 }
20 ▼ if (current -> right){
21 stk.push({current->right, {length + 1, sum + current->right->val}});
22 }
23 ▼ if ( current ->left){
24 stk.push({current->left, {length + 1, sum + current->left->val}});
25 }
26 }
27 return maxSum;
28 }
Test Expected Got

 int arr[] = {-1,0,0,2,2,3,3,5}; 18 18 


int value[] = {1,5,4,7,12,4,8,2};
BTNode* root = BTNode::createTree(arr, arr + sizeof(arr)/sizeof(int), value);
cout << longestPathSum(root);

 int arr[] = {-1,0,1,0,1,4,5,3,7,3}; 61 61 


int value[] = {6,12,23,20,20,20,3,9,13,15};
BTNode* root = BTNode::createTree(arr, arr + sizeof(arr)/sizeof(int), value);
cout << longestPathSum(root);

Passed all tests! 

Chính xác
Điểm cho bài nộp này: 1,00/1,00.
Câu hỏi 9
Chính xác

Điểm 1,00 của 1,00

Class BTNode is used to store a node in binary tree, described on the following:

class BTNode {
public:
int val;
BTNode *left;
BTNode *right;
BTNode() {
this->left = this->right = NULL;
}
BTNode(int val) {
this->val = val;
this->left = this->right = NULL;
}
BTNode(int val, BTNode*& left, BTNode*& right) {
this->val = val;
this->left = left;
this->right = right;
}
};

Where val is the value of node (non-negative integer), left and right are the pointers to the left node and right node of it,
respectively.

Request: Implement function:

int lowestAncestor(BTNode* root, int a, int b);


Where root is the root node of given binary tree (this tree has between 2 and 100000 elements). This function returns the
lowest ancestor node's val of node a and node b in this binary tree (assume a and b always exist in the given binary tree).

More information:

- A node is called as the lowest ancestor node of node a and node b if node a and node b are its descendants.

- A node is also the descendant of itself.

- On the given binary tree, each node's val is distinguish from the others' val

Example:

Given a binary tree in the following:

- The lowest ancestor of node 4 and node 5 is node 2.

Explanation of function createTree: The function has three parameters. The first two parameters take in an array containing
the parent of each Node of the binary tree, and the third parameter takes in an array representing the respective values of the
Nodes. After processing, the function will construct the binary tree and return the address of the root Node. Note that the root
Node is designated with a parent value of -1.

Example:
int arr[] = {-1,0,0,2,2};
int value[] = {3,5,2,1,4};
BTNode* root = BTNode::createTree(arr, arr + sizeof(arr)/sizeof(int), value);
arr[0]=-1 means the Node containing the value value[0]=3 will be the root Node. Also, since arr[1]=arr[2]=0, it implies that
the Nodes containing the values value[1]=5 and value[2]=2 will have the Node containing the value value[0]=3 as their parent.
Lastly, since arr[3]=arr[4]=2, it means the Nodes containing the values value[3]=1 and value[4]=4 will have the Node with the
value value[2]=2 as their parent. Final tree of this example are shown in the figure above.
Note that whichever Node appears first in the arr sequence will be the left Node, and the TestCase always ensures that the
resulting tree is a binary tree.

Note: In this exercise, the libraries iostream, stack, queue, utility and using namespace std are used. You can write helper
functions; however, you are not allowed to use other libraries.

For example:

Test Result

int arr[] = {-1,0,0,2,2,3,3}; 2


BTNode* root = BTNode::createTree(arr, arr + sizeof(arr) / sizeof(int), NULL);
cout << lowestAncestor(root, 4, 5);

int arr[] = {-1,0,1,1,0,4,4,2,5,6}; 4


BTNode* root = BTNode::createTree(arr, arr + sizeof(arr) / sizeof(int), NULL);
cout << lowestAncestor(root, 4, 9);

Answer: (penalty regime: 0 %)

Reset answer

1 ▼ BTNode* lowestCommonAncestor(BTNode* root, int a, int b) {


2 ▼ if (root == nullptr || root->val == a || root->val == b) {
3 return root;
4 }
5
6 BTNode* left = lowestCommonAncestor(root->left, a, b);
7 BTNode* right = lowestCommonAncestor(root->right, a, b);
8
9 ▼ if (left != nullptr && right != nullptr) {
10 return root;
11 }
12
13 ▼ if (left != nullptr) {
14 return left;
15 }
16
17 ▼ if (right != nullptr) {
18 return right;
19 }
20
21 return nullptr;
22 }
23
24 ▼ int lowestAncestor(BTNode* root, int a, int b) {
25 BTNode* lowestCommonAncestorNode = lowestCommonAncestor(root, a, b);
26 return lowestCommonAncestorNode->val;
27 }
28
Test Expected Got

 int arr[] = {-1,0,0,2,2,3,3}; 2 2 


BTNode* root = BTNode::createTree(arr, arr + sizeof(arr) / sizeof(int), NULL);
cout << lowestAncestor(root, 4, 5);

 int arr[] = {-1,0,1,1,0,4,4,2,5,6}; 4 4 


BTNode* root = BTNode::createTree(arr, arr + sizeof(arr) / sizeof(int), NULL);
cout << lowestAncestor(root, 4, 9);

Passed all tests! 

Chính xác
Điểm cho bài nộp này: 1,00/1,00.
Câu hỏi 10
Chính xác

Điểm 1,00 của 1,00

Class BTNode is used to store a node in binary tree, described on the following:

class BTNode {
public:
int val;
BTNode *left;
BTNode *right;
BTNode() {
this->left = this->right = NULL;
}
BTNode(int val) {
this->val = val;
this->left = this->right = NULL;
}
BTNode(int val, BTNode*& left, BTNode*& right) {
this->val = val;
this->left = left;
this->right = right;
}
};

Where val is the value of node (integer, in segment [0,9]), left and right are the pointers to the left node and right node of it,
respectively.

Request: Implement function:

int sumDigitPath(BTNode* root);


Where root is the root node of given binary tree (this tree has between 2 and 100000 elements). This function returns the sum
of all digit path numbers of this binary tree (the result may be large, so you must use mod 27022001 before returning).

More information:

- A path is called as digit path if it is a path from the root node to the leaf node of the binary tree.

- Each digit path represents a number in order, each node's val of this path is a digit of this number, while root's val is
the first digit.
Example:

Given a binary tree in the following:

All of the digit paths are 3-5, 3-2-1, 3-2-4; and the number reprensted by them are 35, 321, 324, respectively. The sum of
them (after mod 27022001) is 680.

Explanation of function createTree: The function has three parameters. The first two parameters take in an array containing
the parent of each Node of the binary tree, and the third parameter takes in an array representing the respective values of the
Nodes. After processing, the function will construct the binary tree and return the address of the root Node. Note that the root
Node is designated with a parent value of -1.

Example:
int arr[] = {-1,0,0,2,2};
int value[] = {3,5,2,1,4};
BTNode* root = BTNode::createTree(arr, arr + sizeof(arr)/sizeof(int), value);

arr[0]=-1 means the Node containing the value value[0]=3 will be the root Node. Also, since arr[1]=arr[2]=0, it implies that the Nodes
containing the values value[1]=5 and value[2]=2 will have the Node containing the value value[0]=3 as their parent. Lastly, since
arr[3]=arr[4]=2, it means the Nodes containing the values value[3]=1 and value[4]=4 will have the Node with the value value[2]=2 as
their parent. Final tree of this example are shown in the figure above.
Note that whichever Node appears first in the arr sequence will be the left Node, and the TestCase always ensures that the resulting tree
is a binary tree.

Note: In this exercise, the libraries iostream, queue, stack, utility and using namespace std are used. You can write helper
functions; however, you are not allowed to use other libraries.

For example:

Test Result

int arr[] = {-1,0,0,2,2}; 680


int value[] = {3,5,2,1,4};
BTNode* root = BTNode::createTree(arr, arr + sizeof(arr)/sizeof(int), value);
cout << sumDigitPath(root);

int arr[] = {-1,0,0}; 25


int value[] = {1,2,3};
BTNode* root = BTNode::createTree(arr, arr + sizeof(arr)/sizeof(int), value);
cout << sumDigitPath(root);

Answer: (penalty regime: 0 %)

Reset answer

1 ▼ void helper(BTNode* node, int pathSum, int& totalSum) {


2 ▼ if (node == nullptr) {
3 return;
4 }
5
6 pathSum = (pathSum * 10 + node->val) % 27022001;
7
8 ▼ if (node->left == nullptr && node->right == nullptr) {
9 totalSum = (totalSum + pathSum) % 27022001;
10 return;
11 }
12 helper(node->left, pathSum, totalSum);
13 helper(node->right, pathSum, totalSum);
14 }
15
16 ▼ int sumDigitPath(BTNode* root) {
17 int sum = 0;
18 helper(root, 0, sum);
19 return sum % 27022001;
20 }
Test Expected Got

 int arr[] = {-1,0,0,2,2}; 680 680 


int value[] = {3,5,2,1,4};
BTNode* root = BTNode::createTree(arr, arr + sizeof(arr)/sizeof(int), value);
cout << sumDigitPath(root);

 int arr[] = {-1,0,0}; 25 25 


int value[] = {1,2,3};
BTNode* root = BTNode::createTree(arr, arr + sizeof(arr)/sizeof(int), value);
cout << sumDigitPath(root);

Passed all tests! 

Chính xác
Điểm cho bài nộp này: 1,00/1,00.
Câu hỏi 11
Chính xác

Điểm 1,00 của 1,00

Given class BinaryTree, you need to finish methods getHeight(), preOrder(), inOrder(), postOrder().

#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>
using namespace std;

template<class K, class V>


class BinaryTree
{
public:
class Node;
private:
Node* root;
public:
BinaryTree() : root(nullptr) {}
~BinaryTree()
{
// You have to delete all Nodes in BinaryTree. However in this task, you can ignore it.
}
class Node
{
private:
K key;
V value;
Node* pLeft, * pRight;
friend class BinaryTree<K, V>;
public:
Node(K key, V value) : key(key), value(value), pLeft(NULL), pRight(NULL) {}
~Node() {}
};
void addNode(string posFromRoot, K key, V value)
{
if (posFromRoot == "")
{
this->root = new Node(key, value);
return;
}
Node* walker = this->root;
int l = posFromRoot.length();
for (int i = 0; i < l - 1; i++)
{
if (!walker)
return;
if (posFromRoot[i] == 'L')
walker = walker->pLeft;
if (posFromRoot[i] == 'R')
walker = walker->pRight;
}
if (posFromRoot[l - 1] == 'L')
walker->pLeft = new Node(key, value);
if (posFromRoot[l - 1] == 'R')
walker->pRight = new Node(key, value);
}
// STUDENT ANSWER BEGIN

// STUDENT ANSWER END


};
For example:

Test Result

BinaryTree<int, int> binaryTree; 2


binaryTree.addNode("", 2, 4); // Add to root 4 6 9
binaryTree.addNode("L", 3, 6); // Add to root's left node 6 4 9
binaryTree.addNode("R", 5, 9); // Add to root's right node 6 9 4

cout << binaryTree.getHeight() << endl;


cout << binaryTree.preOrder() << endl;
cout << binaryTree.inOrder() << endl;
cout << binaryTree.postOrder() << endl;

Answer: (penalty regime: 0 %)

Reset answer

53 ▼ string preOrder() {
54 // TODO: return the sequence of values of nodes in pre-order.
55 stringstream ss;
56 preOrder(root, ss);
57 return ss.str();
58 }
59
60 ▼ string inOrder() {
61 // TODO: return the sequence of values of nodes in in-order.
62 stringstream ss;
63 inOrder(root, ss);
64 return ss.str();
65 }
66
67 ▼ string postOrder() {
68 // TODO: return the sequence of values of nodes in post-order.
69 stringstream ss;
70 postOrder(root, ss);
71 return ss.str();
72 }
73
74 // STUDENT ANSWER END

Test Expected Got

 BinaryTree<int, int> binaryTree; 2 2 


binaryTree.addNode("", 2, 4); // Add to root 4 6 9 4 6 9
binaryTree.addNode("L", 3, 6); // Add to root's left 6 4 9 6 4 9
node 6 9 4 6 9 4
binaryTree.addNode("R", 5, 9); // Add to root's
right node

cout << binaryTree.getHeight() << endl;


cout << binaryTree.preOrder() << endl;
cout << binaryTree.inOrder() << endl;
cout << binaryTree.postOrder() << endl;

 BinaryTree<int, int> binaryTree; 1 1 


binaryTree.addNode("", 2, 4); 4 4
4 4
cout << binaryTree.getHeight() << endl; 4 4
cout << binaryTree.preOrder() << endl;
cout << binaryTree.inOrder() << endl;
cout << binaryTree.postOrder() << endl;
Test Expected Got

 BinaryTree<int, int> binaryTree; 3 3 


binaryTree.addNode("", 2, 4); 4 6 10 2 9 4 6 10 2 9
binaryTree.addNode("L", 3, 6); 10 6 2 4 9 10 6 2 4 9
binaryTree.addNode("R", 5, 9); 10 2 6 9 4 10 2 6 9 4
binaryTree.addNode("LL", 4, 10);
binaryTree.addNode("LR", 6, 2);

cout << binaryTree.getHeight() << endl;


cout << binaryTree.preOrder() << endl;
cout << binaryTree.inOrder() << endl;
cout << binaryTree.postOrder() << endl;

 BinaryTree<int, int> binaryTree; 3 3 


binaryTree.addNode("", 2, 4); 4 6 10 9 2 4 6 10 9 2
binaryTree.addNode("L", 3, 6); 10 6 4 2 9 10 6 4 2 9
binaryTree.addNode("R", 5, 9); 10 6 2 9 4 10 6 2 9 4
binaryTree.addNode("LL", 4, 10);
binaryTree.addNode("RL", 6, 2);

cout << binaryTree.getHeight() << endl;


cout << binaryTree.preOrder() << endl;
cout << binaryTree.inOrder() << endl;
cout << binaryTree.postOrder() << endl;

 BinaryTree<int, int> binaryTree; 5 5 


binaryTree.addNode("",2, 4); 4 6 10 2 7 9 4 6 10 2 7 9
binaryTree.addNode("L",3, 6); 2 7 10 6 4 9 2 7 10 6 4 9
binaryTree.addNode("R",5, 9); 7 2 10 6 9 4 7 2 10 6 9 4
binaryTree.addNode("LL",4, 10);
binaryTree.addNode("LLL",6, 2);
binaryTree.addNode("LLLR",7, 7);

cout << binaryTree.getHeight() << endl;


cout << binaryTree.preOrder() << endl;
cout << binaryTree.inOrder() << endl;
cout << binaryTree.postOrder() << endl;

 BinaryTree<int, int> binaryTree; 5 5 


binaryTree.addNode("",2, 4); 4 6 10 2 7 9 307 30 4 6 10 2 7 9 307 30
binaryTree.addNode("L",3, 6); 2 7 10 6 4 307 9 30 2 7 10 6 4 307 9 30
binaryTree.addNode("R",5, 9); 7 2 10 6 307 30 9 4 7 2 10 6 307 30 9 4
binaryTree.addNode("LL",4, 10);
binaryTree.addNode("LLL",6, 2);
binaryTree.addNode("LLLR",7, 7);
binaryTree.addNode("RR",8, 30);
binaryTree.addNode("RL",9, 307);

cout << binaryTree.getHeight() << endl;


cout << binaryTree.preOrder() << endl;
cout << binaryTree.inOrder() << endl;
cout << binaryTree.postOrder() << endl;
Test Expected Got

 BinaryTree<int, int> binaryTree; 5 5 


binaryTree.addNode("",2, 4); 4 6 10 2 7 -3 9 307 30 4 6 10 2 7 -3 9 307 30
binaryTree.addNode("L",3, 6); 2 7 10 6 -3 4 307 9 30 2 7 10 6 -3 4 307 9 30
binaryTree.addNode("R",5, 9); 7 2 10 -3 6 307 30 9 4 7 2 10 -3 6 307 30 9 4
binaryTree.addNode("LL",4, 10);
binaryTree.addNode("LR",6, -3);
binaryTree.addNode("LLL",7, 2);
binaryTree.addNode("LLLR",8, 7);
binaryTree.addNode("RR",9, 30);
binaryTree.addNode("RL",10, 307);

cout << binaryTree.getHeight() << endl;


cout << binaryTree.preOrder() << endl;
cout << binaryTree.inOrder() << endl;
cout << binaryTree.postOrder() << endl;

 BinaryTree<int, int> binaryTree; 5 5 


binaryTree.addNode("",2, 4); 4 6 10 2 7 -3 9 307 2000 4 6 10 2 7 -3 9 307 2000
binaryTree.addNode("L",3, 6); 2000 30 2000 30
binaryTree.addNode("R",5, 9); 2 7 10 6 -3 4 2000 307 2000 2 7 10 6 -3 4 2000 307 2000
binaryTree.addNode("LL",4, 10); 9 30 9 30
binaryTree.addNode("LR",6, -3); 7 2 10 -3 6 2000 2000 307 30 7 2 10 -3 6 2000 2000 307
binaryTree.addNode("LLL",7, 2); 9 4 30 9 4
binaryTree.addNode("LLLR",8, 7);
binaryTree.addNode("RR",9, 30);
binaryTree.addNode("RL",10, 307);
binaryTree.addNode("RLL",11, 2000);
binaryTree.addNode("RLR",12, 2000);

cout << binaryTree.getHeight() << endl;


cout << binaryTree.preOrder() << endl;
cout << binaryTree.inOrder() << endl;
cout << binaryTree.postOrder() << endl;

 BinaryTree<int, int> binaryTree; 5 5 


binaryTree.addNode("",2, 4); 4 6 10 2 7 -3 9 307 2000 30 4 6 10 2 7 -3 9 307 2000 30
binaryTree.addNode("L",3, 6); 2 7 10 6 -3 4 2000 307 9 30 2 7 10 6 -3 4 2000 307 9 30
binaryTree.addNode("R",5, 9); 7 2 10 -3 6 2000 307 30 9 4 7 2 10 -3 6 2000 307 30 9 4
binaryTree.addNode("LL",4, 10);
binaryTree.addNode("LR",6, -3);
binaryTree.addNode("LLL",7, 2);
binaryTree.addNode("LLLR",8, 7);
binaryTree.addNode("RR",9, 30);
binaryTree.addNode("RL",10, 307);
binaryTree.addNode("RLL",11, 2000);

cout << binaryTree.getHeight() << endl;


cout << binaryTree.preOrder() << endl;
cout << binaryTree.inOrder() << endl;
cout << binaryTree.postOrder() << endl;
Test Expected Got

 BinaryTree<int, int> binaryTree; 5 5 


binaryTree.addNode("",2, 4); 4 6 10 2 7 -3 9 307 2000 4 6 10 2 7 -3 9 307 2000
binaryTree.addNode("L",3, 6); 2000 30 2000 30
binaryTree.addNode("R",5, 9); 2 7 10 6 -3 4 2000 2000 307 2 7 10 6 -3 4 2000 2000 307
binaryTree.addNode("LL",4, 10); 9 30 9 30
binaryTree.addNode("LR",6, -3); 7 2 10 -3 6 2000 2000 307 30 7 2 10 -3 6 2000 2000 307
binaryTree.addNode("LLL",7, 2); 9 4 30 9 4
binaryTree.addNode("LLLR",8, 7);
binaryTree.addNode("RR",9, 30);
binaryTree.addNode("RL",10, 307);
binaryTree.addNode("RLL",11, 2000);
binaryTree.addNode("RLLL",11, 2000);

cout << binaryTree.getHeight() << endl;


cout << binaryTree.preOrder() << endl;
cout << binaryTree.inOrder() << endl;
cout << binaryTree.postOrder() << endl;

Passed all tests! 

Chính xác
Điểm cho bài nộp này: 1,00/1,00.
Câu hỏi 12
Chính xác

Điểm 1,00 của 1,00

In this question, you have to perform add and delete on binary search tree. Note that:

- When deleting a node which still have 2 children, take the inorder successor (smallest node of the right sub tree of that node) to replace it.

- When adding a node which has the same value as parent node, add it in the left sub tree.

Your task is to implement two functions: add and deleteNode. You could define one or more functions to achieve this task.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
#define SEPARATOR "#<ab@17943918#@>#"
template<class T>
class BinarySearchTree
{
public:
class Node;
private:
Node* root;
public:
BinarySearchTree() : root(nullptr) {}
~BinarySearchTree()
{
// You have to delete all Nodes in BinaryTree. However in this task, you can ignore it.
}

//Helping function

void add(T value){


//TODO
}

void deleteNode(T value){


//TODO
}
string inOrderRec(Node* root) {
stringstream ss;
if (root != nullptr) {
ss << inOrderRec(root->pLeft);
ss << root->value << " ";
ss << inOrderRec(root->pRight);
}
return ss.str();
}

string inOrder(){
return inOrderRec(this->root);
}

class Node
{
private:
T value;
Node* pLeft, * pRight;
friend class BinarySearchTree<T>;
public:
Node(T value) : value(value), pLeft(NULL), pRight(NULL) {}
~Node() {}
};
};
For example:

Test Result

BinarySearchTree<int> bst; 2 10
bst.add(9);
bst.add(2);
bst.add(10);
bst.deleteNode(9);
cout << bst.inOrder();

BinarySearchTree<int> bst; 2 8 9 10
bst.add(9); 2 8 10 11
bst.add(2);
bst.add(10);
bst.add(8);
cout << bst.inOrder()<<endl;
bst.add(11);
bst.deleteNode(9);
cout << bst.inOrder();

Answer: (penalty regime: 0 %)

Reset answer

1 //Helping functions
2 ▼ Node* addHelper(Node* node, T value) {
3 ▼ if (node == nullptr) {
4 return new Node(value);
5 }
6
7 ▼ if (value < node->value) {
8 node->pLeft = addHelper(node->pLeft, value);
9 ▼ } else {
10 node->pRight = addHelper(node->pRight, value);
11 }
12
13 return node;
14 }
15
16 ▼ Node* getInorderSuccessor(Node* node) {
17 Node* current = node;
18 ▼ while (current && current->pLeft != nullptr) {
19 current = current->pLeft;
20 }
21 return current;
22 }
23
24 ▼ Node* deleteHelper(Node* node, T value) {
25 ▼ if (node == nullptr) {
26 return node;
27 }
28
29 ▼ if (value < node->value) {
30 node->pLeft = deleteHelper(node->pLeft, value);
31 ▼ } else if (value > node->value) {
32 node->pRight = deleteHelper(node->pRight, value);
33 ▼ } else {
34
35 ▼ if (node->pLeft == nullptr) {
36 Node* temp = node->pRight;
37 delete node;
38 return temp;
39 ▼ } else if (node->pRight == nullptr) {
40 Node* temp = node->pLeft;
41 delete node;
42 return temp;
43 }
44
45 Node* successor = getInorderSuccessor(node->pRight);
46 node->value = successor->value;
47 node->pRight = deleteHelper(node->pRight, successor->value);
48 }
49
50 return node;
51 }
52 ▼ void add(T value){
53 root = addHelper(root, value);
54 }
55
56 ▼ void deleteNode(T value){
57 root = deleteHelper(root, value);
58
59 }

Test Expected Got

 BinarySearchTree<int> bst; 2 10 2 10 
bst.add(9);
bst.add(2);
bst.add(10);
bst.deleteNode(9);
cout << bst.inOrder();

 BinarySearchTree<int> bst; 2 8 9 10 2 8 9 10 
bst.add(9); 2 8 10 11 2 8 10 11
bst.add(2);
bst.add(10);
bst.add(8);
cout << bst.inOrder()<<endl;
bst.add(11);
bst.deleteNode(9);
cout << bst.inOrder();

Passed all tests! 

Chính xác
Điểm cho bài nộp này: 1,00/1,00.
Câu hỏi 13
Chính xác

Điểm 1,00 của 1,00

Class BSTNode is used to store a node in binary search tree, described on the following:

class BSTNode {
public:
int val;
BSTNode *left;
BSTNode *right;
BSTNode() {
this->left = this->right = nullptr;
}
BSTNode(int val) {
this->val = val;
this->left = this->right = nullptr;
}
BSTNode(int val, BSTNode*& left, BSTNode*& right) {
this->val = val;
this->left = left;
this->right = right;
}
};

Where val is the value of node, left and right are the pointers to the left node and right node of it, respectively. If a repeated value is
inserted to the tree, it will be inserted to the left subtree.

Also, a static method named createBSTree is used to create the binary search tree, by iterating the argument array left-to-right and repeatedly
calling addNode method on the root node to insert the value into the correct position. For example:
int arr[] = {0, 10, 20, 30};
auto root = BSTNode::createBSTree(arr, arr + 4);

is equivalent to
auto root = new BSTNode(0);
root->addNode(10);
root->addNode(20);
root->addNode(30);

Request: Implement function:

vector<int> levelAlterTraverse(BSTNode* root);


Where root is the root node of given binary search tree (this tree has between 0 and 100000 elements). This function returns the values of the
nodes in each level, alternating from going left-to-right and right-to-left..
Example:

Given a binary search tree in the following:

In the first level, we should traverse from left to right (order: 3) and in the second level, we traverse from right to left (order: 4, 0). After
traversing all the nodes, the result should be [3, 4, 0, 2, 1].
Note: In this exercise, the libraries iostream, vector, stack, queue, algorithm and using namespace std are used. You can write helper functions;
however, you are not allowed to use other libraries.
For example:

Test Result

int arr[] = {0, 3, 5, 1, 2, 4}; [0, 3, 1, 5, 4, 2]


BSTNode* root = BSTNode::createBSTree(arr, arr + sizeof(arr)/sizeof(int));
printVector(levelAlterTraverse(root));
BSTNode::deleteTree(root);

Answer: (penalty regime: 0 %)

Reset answer

14
15 ▼ for (int i = 0; i < levelSize; i++) {
16 BSTNode* node = q.front();
17 q.pop();
18
19 int index = leftToRight ? i : levelSize - i - 1;
20 levelValues[index] = node->val;
21
22 ▼ if (node->left != nullptr) {
23 q.push(node->left);
24 }
25 ▼ if (node->right != nullptr) {
26 q.push(node->right);
27 }
28 }
29
30 result.insert(result.end(), levelValues.begin(), levelValues.end());
31 leftToRight = !leftToRight;
32 }
33
34 return result;
35 }

Test Expected Got

 int arr[] = {0, 3, 5, 1, 2, 4}; [0, 3, 1, 5, 4, 2] [0, 3, 1, 5, 4, 2] 


BSTNode* root = BSTNode::createBSTree(arr, arr + sizeof(arr)/sizeof(int));
printVector(levelAlterTraverse(root));
BSTNode::deleteTree(root);

Passed all tests! 

Chính xác
Điểm cho bài nộp này: 1,00/1,00.
Câu hỏi 14
Chính xác

Điểm 1,00 của 1,00

Class BSTNode is used to store a node in binary search tree, described on the following:

class BSTNode {
public:
int val;
BSTNode *left;
BSTNode *right;
BSTNode() {
this->left = this->right = nullptr;
}
BSTNode(int val) {
this->val = val;
this->left = this->right = nullptr;
}
BSTNode(int val, BSTNode*& left, BSTNode*& right) {
this->val = val;
this->left = left;
this->right = right;
}
};

Where val is the value of node, left and right are the pointers to the left node and right node of it, respectively. If a repeated value is
inserted to the tree, it will be inserted to the left subtree.

Also, a static method named createBSTree is used to create the binary search tree, by iterating the argument array left-to-right and repeatedly
calling addNode method on the root node to insert the value into the correct position. For example:
int arr[] = {0, 10, 20, 30};
auto root = BSTNode::createBSTree(arr, arr + 4);

is equivalent to
auto root = new BSTNode(0);
root->addNode(10);
root->addNode(20);
root->addNode(30);

Request: Implement function:

int kthSmallest(BSTNode* root, int k);


Where root is the root node of given binary search tree (this tree has n elements) and k satisfy: 1 <= k <= n <= 100000. This function returns
the k-th smallest value in the tree.

Example:
Given a binary search tree in the following:
With k = 2, the result should be 1.

Note: In this exercise, the libraries iostream, vector, stack, queue, algorithm, climits and using namespace std are used. You can write helper
functions; however, you are not allowed to use other libraries.
For example:

Test Result

int arr[] = {6, 9, 2, 13, 0, 20}; 2


int k = 2;
BSTNode* root = BSTNode::createBSTree(arr, arr + sizeof(arr)/sizeof(int));
cout << kthSmallest(root, k);
BSTNode::deleteTree(root);

Answer: (penalty regime: 0 %)

Reset answer

1 ▼ void kthSmallestHelper(BSTNode* node, int k, int& count, int& result) {


2 if (node == nullptr) return;
3
4 kthSmallestHelper(node->left, k, count, result);
5
6 count++;
7
8 ▼ if (count == k) {
9 result = node->val;
10 return;
11 }
12
13 kthSmallestHelper(node->right, k, count, result);
14 }
15
16 ▼ int kthSmallest(BSTNode* root, int k) {
17 int count = 0;
18 int result;
19 kthSmallestHelper(root, k, count, result);
20 return result;
21 }

Test Expected Got

 int arr[] = {6, 9, 2, 13, 0, 20}; 2 2 


int k = 2;
BSTNode* root = BSTNode::createBSTree(arr, arr + sizeof(arr)/sizeof(int));
cout << kthSmallest(root, k);
BSTNode::deleteTree(root);

Passed all tests! 

Chính xác
Điểm cho bài nộp này: 1,00/1,00.
Câu hỏi 15
Chính xác

Điểm 1,00 của 1,00

Class BTNode is used to store a node in binary search tree, described on the following:

class BTNode {
public:
int val;
BTNode *left;
BTNode *right;
BTNode() {
this->left = this->right = NULL;
}
BTNode(int val) {
this->val = val;
this->left = this->right = NULL;
}
BTNode(int val, BTNode*& left, BTNode*& right) {
this->val = val;
this->left = left;
this->right = right;
}
};

Where val is the value of node (non-negative integer), left and right are the pointers to the left node and right node of it,
respectively.

Also, a static method named createBSTree is used to create the binary search tree, by iterating the argument array left-to-right
and repeatedly calling addNode method on the root node to insert the value into the correct position. For example:
int arr[] = {0, 10, 20, 30};
auto root = BSTNode::createBSTree(arr, arr + 4);

is equivalent to
auto root = new BSTNode(0);
root->addNode(10);
root->addNode(20);
root->addNode(30);

Request: Implement function:

int rangeCount(BTNode* root, int lo, int hi);


Where root is the root node of given binary search tree (this tree has between 0 and 100000 elements), lo and hi are 2 positives
integer and lo ≤ hi. This function returns the number of all nodes whose values are between [lo, hi] in this binary search tree.

More information:

- If a node has val which is equal to its ancestor's, it is in the right subtree of its ancestor.

Example:

Given a binary search tree in the following:


With lo=5, hi=10, all the nodes satisfied are node 9, 7, 8; there fore, the result is 3.

Note: In this exercise, the libraries iostream, stack, queue, utility and using namespace std are used. You can write helper
functions; however, you are not allowed to use other libraries.

For example:

Test Result

int value[] = {3,2,9,7,12,4,8}; 3


int lo = 5, hi = 10;
BTNode* root = BTNode::createBSTree(value, value + sizeof(value)/sizeof(int));
cout << rangeCount(root, lo, hi);

int value[] = {1167,2381,577,2568,124,1519,234,1679,2696,2359}; 4


int lo = 500, hi = 2000;
BTNode* root = BTNode::createBSTree(value, value + sizeof(value)/sizeof(int));
cout << rangeCount(root, lo, hi);

Answer: (penalty regime: 0 %)

Reset answer

1 ▼ int rangeCount(BTNode* root, int lo, int hi) {


2 ▼ if (root == NULL) {
3 return 0;
4 }
5 int count = 0;
6
7 count += rangeCount(root->left, lo, hi);
8 count += rangeCount(root->right, lo, hi);
9
10 ▼ if (root->val >= lo && root->val <= hi) {
11 count++;
12 }
13
14 return count;
15 }
16
Test Expected Got

 int value[] = {3,2,9,7,12,4,8}; 3 3 


int lo = 5, hi = 10;
BTNode* root = BTNode::createBSTree(value, value + sizeof(value)/sizeof(int));
cout << rangeCount(root, lo, hi);

 int value[] = {1167,2381,577,2568,124,1519,234,1679,2696,2359}; 4 4 


int lo = 500, hi = 2000;
BTNode* root = BTNode::createBSTree(value, value + sizeof(value)/sizeof(int));
cout << rangeCount(root, lo, hi);

Passed all tests! 

Chính xác
Điểm cho bài nộp này: 1,00/1,00.
Câu hỏi 16
Chính xác

Điểm 1,00 của 1,00

Class BSTNode is used to store a node in binary search tree, described on the following:

class BSTNode {
public:
int val;
BSTNode *left;
BSTNode *right;
BSTNode() {
this->left = this->right = nullptr;
}
BSTNode(int val) {
this->val = val;
this->left = this->right = nullptr;
}
BSTNode(int val, BSTNode*& left, BSTNode*& right) {
this->val = val;
this->left = left;
this->right = right;
}
};

Where val is the value of node, left and right are the pointers to the left node and right node of it, respectively. If a repeated value is
inserted to the tree, it will be inserted to the left subtree.

Also, a static method named createBSTree is used to create the binary search tree, by iterating the argument array left-to-right and repeatedly
calling addNode method on the root node to insert the value into the correct position. For example:
int arr[] = {0, 10, 20, 30};
auto root = BSTNode::createBSTree(arr, arr + 4);

is equivalent to
auto root = new BSTNode(0);
root->addNode(10);
root->addNode(20);
root->addNode(30);

Request: Implement function:

int singleChild(BSTNode* root);


Where root is the root node of given binary search tree (this tree has between 0 and 100000 elements). This function returns the number of
single children in the tree.
More information:

- A node is called a single child if its parent has only one child.

Example:

Given a binary search tree in the following:


There are 2 single children: node 2 and node 3.

Note: In this exercise, the libraries iostream and using namespace std are used. You can write helper functions; however, you are not allowed to
use other libraries.
For example:

Test Result

int arr[] = {0, 3, 5, 1, 2, 4}; 3


BSTNode* root = BSTNode::createBSTree(arr, arr + sizeof(arr)/sizeof(int));
cout << singleChild(root);
BSTNode::deleteTree(root);

Answer: (penalty regime: 0 %)

Reset answer

1 ▼ int singleChild(BSTNode* root) {


2 ▼ if (root == nullptr || (root->left == nullptr && root->right == nullptr)) {
3 return 0;
4 }
5
6 int count = 0;
7
8 count += singleChild(root->left);
9 count += singleChild(root->right);
10
11 ▼ if ((root->left != nullptr && root->right == nullptr) || (root->left == nullptr && root->right != nullpt
12 count++;
13 }
14
15 return count;
16 }
17

Test Expected Got

 int arr[] = {0, 3, 5, 1, 2, 4}; 3 3 


BSTNode* root = BSTNode::createBSTree(arr, arr + sizeof(arr)/sizeof(int));
cout << singleChild(root);
BSTNode::deleteTree(root);

Passed all tests! 

Chính xác
Điểm cho bài nộp này: 1,00/1,00.
Câu hỏi 17
Chính xác

Điểm 1,00 của 1,00

Class BSTNode is used to store a node in binary search tree, described on the following:

class BSTNode {
public:
int val;
BSTNode *left;
BSTNode *right;
BSTNode() {
this->left = this->right = nullptr;
}
BSTNode(int val) {
this->val = val;
this->left = this->right = nullptr;
}
BSTNode(int val, BSTNode*& left, BSTNode*& right) {
this->val = val;
this->left = left;
this->right = right;
}
};

Where val is the value of node, left and right are the pointers to the left node and right node of it, respectively. If a repeated value is
inserted to the tree, it will be inserted to the left subtree.

Also, a static method named createBSTree is used to create the binary search tree, by iterating the argument array left-to-right and repeatedly
calling addNode method on the root node to insert the value into the correct position. For example:
int arr[] = {0, 10, 20, 30};
auto root = BSTNode::createBSTree(arr, arr + 4);

is equivalent to
auto root = new BSTNode(0);
root->addNode(10);
root->addNode(20);
root->addNode(30);

Request: Implement function:

BSTNode* subtreeWithRange(BSTNode* root, int lo, int hi);


Where root is the root node of given binary search tree (this tree has between 0 and 100000 elements). This function returns the binary search
tree after deleting all nodes whose values are outside the range [lo, hi] (inclusive).

Example:
Given a binary search tree in the following:

With lo = 7 and hi = 10, the result should be:


Note: In this exercise, the libraries iostream and using namespace std are used. You can write helper functions; however, you are not allowed to
use other libraries.
For example:

Test Result

int arr[] = {0, 3, 5, 1, 2, 4}; 3 1 2


int lo = 1, hi = 3;
BSTNode* root = BSTNode::createBSTree(arr, arr + sizeof(arr)/sizeof(int));
root = subtreeWithRange(root, lo, hi);
BSTNode::printPreorder(root);
BSTNode::deleteTree(root);

Answer: (penalty regime: 0 %)

Reset answer

1 ▼ BSTNode* subtreeWithRange(BSTNode* root, int lo, int hi) {


2 ▼ if (root == nullptr) {
3 return nullptr;
4 }
5
6 root->left = subtreeWithRange(root->left, lo, hi);
7 root->right = subtreeWithRange(root->right, lo, hi);
8
9 ▼ if (root->val < lo) {
10 BSTNode* rightSubtree = root->right;
11 delete root;
12 return rightSubtree;
13 }
14
15 ▼ if (root->val > hi) {
16 BSTNode* leftSubtree = root->left;
17 delete root;
18 return leftSubtree;
19 }
20 return root;
21 }
22

Test Expected Got

 int arr[] = {0, 3, 5, 1, 2, 4}; 3 1 2 3 1 2 


int lo = 1, hi = 3;
BSTNode* root = BSTNode::createBSTree(arr, arr + sizeof(arr)/sizeof(int));
root = subtreeWithRange(root, lo, hi);
BSTNode::printPreorder(root);
BSTNode::deleteTree(root);

Passed all tests! 

Chính xác
Điểm cho bài nộp này: 1,00/1,00.
BÁCH KHOA E-LEARNING

WEBSITE

HCMUT
MyBK
BKSI

LIÊN HỆ

 268 Lý Thường Kiệt, P.14, Q.10, TP.HCM

 (028) 38 651 670 - (028) 38 647 256 (Ext: 5258, 5234)

 elearning@hcmut.edu.vn

Copyright 2007-2022 BKEL - Phát triển dựa trên Moodle

You might also like