1064 Complete Binary Search Tree (30 分)
参考:https://blog.csdn.net/richenyunqi/article/details/78868563
1 #pragma warning(disable:4996) 2 #define _CRT_SECURE_NO_WARNINGS 3 4 #include <iostream> 5 #include <algorithm> 6 #include <cmath> 7 #include <vector> 8 #include <map> 9 #include <set> 10 #include <unordered_set> 11 #include <unordered_map> 12 #include <queue> 13 #include <cmath> 14 #include <string> 15 #define INFINITE 65535 16 using namespace std; 17 int A[1010], tree[1010]; 18 void createTree(int left, int right, int index) { 19 //求左子树的个数 20 if (left > right) return; 21 //else if(left == right){ 22 // tree[index] = A[left]; 23 // return; 24 //} 25 int depth = (int)floor(log(right - left + 2)/log(2)); 26 int last_half = pow(2, depth - 1);//最后一层一半 27 int front = 2 * last_half - 1;//除去最后一层的数量 28 int left_last = min(last_half, right - left + 1 - front);//最后一层左子树的数量 29 int root = left + last_half - 1 + left_last;//求出根节点在A中的位置 30 tree[index] = A[root];//给完全二叉树中的根节点赋值 31 //递归处理左右子树 32 createTree(left, root - 1, 2 * index); 33 createTree(root + 1, right, 2 * index + 1); 34 } 35 int main() { 36 int n; 37 cin >> n; 38 for (int i = 0; i < n; ++i) { 39 cin >> A[i]; 40 } 41 sort(A, A + n); 42 createTree(0, n - 1, 1); 43 for (int i = 1; i <= n; ++i) { 44 if (i != 1) cout << " "; 45 cout << tree[i]; 46 } 47 return 0; 48 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步