Skip to content

Commit f0ae7b3

Browse files
authored
Create 6.3.5从二叉树到堆.md
1 parent b271d28 commit f0ae7b3

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

6.3.5从二叉树到堆.md

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
- 问题:给定一组按无序二叉树结构组织的整数,编写数组排序程序将树转换为堆,堆的底层数据结构为平衡二叉树
2+
- 思路:
3+
1. 从最后一个非叶子节点开始,向根节点遍历。最后一个非叶子节点的索引可以通过 **`(n/2)-1`** 计算,其中 **`n`** 是节点的总数。这是因为叶子节点本身可以看作是已经满足堆性质的堆。
4+
2. 对于每个非叶子节点,检查它与其子节点的关系,确保父节点的值比子节点的值大(对于最小堆)或小(对于最大堆)。如果父节点的值不符合堆性质,需要交换父节点与子节点的值,以满足堆性质。
5+
3. 重复步骤2,直到所有节点都满足堆性质。
6+
7+
```cpp
8+
#include <iostream>
9+
#include <vector>
10+
using namespace std;
11+
12+
struct TreeNode{
13+
TreeNode* lChild;
14+
TreeNode* rChild;
15+
int value;
16+
TreeNode(int val) : value(val), lChild(nullptr), rChild(nullptr) {}
17+
};
18+
19+
void Heapify(vector<int>& array, int parent){
20+
int n = array.size();
21+
int lChildIndex = parent * 2 + 1;
22+
int rChildIndex = parent * 2 + 2;
23+
int targetIndex = parent;
24+
if(lChildIndex < n && lChildIndex >= 0 && array[targetIndex] < array[lChildIndex]){
25+
targetIndex = lChildIndex;
26+
}
27+
if(rChildIndex < n && rChildIndex >= 0 && array[targetIndex] < array[rChildIndex]){
28+
targetIndex = rChildIndex;
29+
}
30+
if(parent != targetIndex){
31+
swap(array[targetIndex], array[parent]);
32+
Heapify(array, targetIndex);
33+
}
34+
}
35+
36+
void BuildHeap(vector<int>& array){
37+
int n = array.size();
38+
for(int i = n/2-1; i >= 0; i--){
39+
Heapify(array, i);
40+
}
41+
}
42+
43+
int main(){
44+
vector<int> arr = {4, 10, 3, 5, 1};
45+
int n = arr.size();
46+
47+
cout << "Original Array: ";
48+
for (int num : arr) {
49+
cout << num << " ";
50+
}
51+
cout << endl;
52+
53+
BuildHeap(arr);
54+
55+
cout << "New Array: ";
56+
for (int num : arr) {
57+
cout << num << " ";
58+
}
59+
cout << endl;
60+
}
61+
```

0 commit comments

Comments
 (0)