Bài tập Tuần 7 – Cây nhị phân Bài 1 Cho cây nhị phân tìm kiếm BST Binary Search Tree, định nghĩa như sau // Node of BST Tree struct Node { int data; Node *pLeft; Node *pRight; }; // Hàm tạo một node N[.]
Trang 1Bài tập Tuần 7 – Cây nhị phân Bài 1
Cho cây nhị phân tìm kiếm -BST- Binary Search Tree, định nghĩa như sau: // Node of BST Tree
struct Node {
int data;
Node *pLeft;
Node *pRight;
};
// Hàm tạo một node
Node* newNode(int data) {
Node* tmp = new Node;
tmp->data = data;
tmp->pLeft = tmp->pRight = NULL;
return tmp;
}
a) Viết hàm tìm một node có khoá 'key'
Node* searchBST(Node* pRoot, int key);
b) Tìm các node có khoá gần với x nhất
Node* search_nearX(Node* pRoot, int x);
c) Viết hàm thêm một node với khoá 'key'
Node* insertBST(Node* node, int key);
d) Tạo 1 cây BST và kiểm thử các hàm đã viết
Bài 2
Cho cây nhị phân định nghĩa như sau
// A binary tree node
struct Node {
int data;
Node *pLeft, *pRight;
};
a) Viết hàm duyệt cây theo thứ tự Inorder(Left, Root, Right)
b) Viết hàm duyệt cây theo thứ tự preorder(Root, Left, Right)
c) Viết hàm duyệt cây theo thứ tự postorder(Left, Right, Root)
Trang 2d) Viết hàm duyệt cây nhị phân theo chiều rộng (Duyệt theo mức)
void BFS_traversal(Node *pRoot);
input:
Output:
25 15 50 10 22 35 70 4 12 18 24 31 44 66 90
Bài 3
Cho cây nhị phân định nghĩa như sau
// A binary tree node
struct Node {
int data;
Node *pLeft, *pRight;
};
a) Viết hàm xoá một nút khỏi cây nhị phân
Trang 3b) Viết hàm thêm một node vào cây nhị phân theo mức
Sau khi thêm node 12 Bài 4 – Cấu trúc Heap, Binary Heap
Cấu trúc Heap định nghĩa như sau:
// Cấu trúc Heap
struct Heap {
int heap_size;
int *harr;
int capacity;
};
// Hàm tạo một Heap
Heap * creatHeap( int capacity ) {
Heap * heap = new Heap ;
heap->harr = new int ;
heap->heap_size = 0;
heap->capacity = capacity ;
return heap;
}
Hãy viết các hàm thao tác trên cấu trúc Heap:
1 Viết hàm Heapify()
void Heapify(Heap* h, int i)
Trang 42 Viết hàm extractMin
int extractMin(Heap* h)
3 Thêm một khoá ‘k’ vào Heap
void insertKey(Heap* heap, int k)
4 Xoá một khoá tại một chỉ mục ‘i’
void deleteKey(Heap* h, int i)
5 Viết chương trình tạo một Heap và kiểm thử lại các hàm đã viết Hướng dẫn: Xem cấu trúc Heap
Link: https://towardsdatascience.com/data-structure-heap-23d4c78a6962
======================== ** * ** ========================