1.用数组模拟树
这里用一个够大的一维数组存储这颗树,某内点的左子树下标为该内点的2倍,右子树为该内点下标的2倍加一。
内点下标:i
左子树下标:2 * i
右子树下标:2 * i + 1
#include<iostream>
using namespace std;
const int max_n = 32768;
int tree[max_n];
int Creat(int *node, int len) {
int max = 1;
tree[1] = node[1];
for (int i = 2; i <= len; ++i) {
int level = 1;
while (tree[level]) {
if (node[i] < tree[level]) level *= 2;
else level = 2 * level + 1;
if (max < level) max = level;
}
tree[level] = node[i];
}
return max;
}
int main() {
int node[100], n, num;
cin >> n;
for (int i = 1; i <= n; ++i) cin >> node[i];
num = Creat(node, n);
for (int i = 1; i <= num; ++i) cout << tree[i] << " ";
}
用数组模拟的树来建立二叉查找树:
//建立二叉查找树
#include<iostream>
using