基本思想:
一定要注意以下几个关键点:
1.二叉排序树的中序遍历是有序序列;
2.完全二叉树使用数组存储时可以直接初始化,可以不初始化直接三种顺序访问;
关键点:
无;
#include<iostream> #include<stdlib.h> #include<stdio.h> #include<vector> #include<string> #include<math.h> #include<algorithm> #include<cstring> #include<map> #include<queue> using namespace std; vector<int>seq; vector<int>layer; int tree[1020]; int n; int st = 0; void inorder(int index) { if (index > n) return; inorder(index * 2); tree[index] = seq[st++]; inorder(index * 2 + 1); } void layer_find() { queue<int>q; q.push(1); while (!q.empty()){ int index = q.front(); layer.push_back(tree[index]); q.pop(); if (index * 2 <= n) { q.push(index * 2); } if (index * 2+1 <= n) { q.push(index * 2 + 1); } } } int main() { fill(tree, tree + 1020, -1); int a; cin >> n; seq.resize(n); for (int i = 0; i < n; i++) { cin >> seq[i]; } sort(seq.begin(), seq.end()); inorder(1); layer_find(); for (int i = 0; i < n;i++) { if (i == 0) cout << layer[i]; else cout << " " << layer[i]; } return 0; }
1064 Complete Binary Search Tree (30point(s)) 需要二刷 *二叉排序树和完全二叉树之间的联系
原文:https://www.cnblogs.com/songlinxuan/p/12300312.html