晴神笔记十分贴心呐,我就是那种对指针写法信心不足的读者。所以下面来看看数组实现二叉树吧~
静态二叉链表
- 将struct Node的指针域用int代替,表示左右子树根结点在数组中的下标。
- 由于需要用到下标,要预先开一个大小为结点上限个数的Node型数组。
- 以下标为“ -1”表示孩子结点为空。
例
1102 Invert a Binary Tree (25 分)
⚠️%c格式化输入时,getchar()吞掉前面的换行符,或者scanf("%*c%c %c", lc, rc);
也可,getchar()
、%*c
这两种写法可以吞掉任意一个字符。
⚠️此题要求反转左右子树,建树时反转最方便。
⚠️找出根:不是任何结点的孩子结点的结点就是根。
#include
#include
#include
#define MAXN 10
using namespace std;
int nn, cnt1, cnt2;
bool ancestor[MAXN];
struct Node {
int lchild = -1, rchild = -1;
} btree[MAXN];
void level_order(int root) {
queue mq;
mq.push(root);
while (!mq.empty()) {
int curr = mq.front();
printf("%d", curr);
cnt1++;
if (cnt1 < nn) printf(" ");
mq.pop();
if (btree[curr].lchild != -1)
mq.push(btree[curr].lchild);
if (btree[curr].rchild != -1)
mq.push(btree[curr].rchild);
}
}
void in_order(int root) {
if (btree[root].lchild != -1) {
in_order(btree[root].lchild);
}
cnt2++;
printf("%d", root);
if (cnt2 < nn) printf(" ");
if (btree[root].rchild != -1) {
in_order(btree[root].rchild);
}
}
int main() {
fill(ancestor, ancestor + MAXN, true);
scanf("%d", &nn);
char lc, rc;
for (int i = 0; i < nn; ++i) {
getchar();
scanf("%c %c", &lc, &rc);
if (lc != '-') {
btree[i].rchild = lc - '0';
ancestor[lc - '0'] = false;
}
if (rc != '-') {
btree[i].lchild = rc - '0';
ancestor[rc - '0'] = false;
}
}
int root;
for (int i = 0; i < nn; ++i) {
if (ancestor[i]) {
root = i;
break;
}
}
cnt1 = cnt2 = 0;
level_order(root);
puts("");
in_order(root);
return 0;
}
1099 Build A Binary Search Tree (30 分)
#include
#include
#include
using namespace std;
struct Node {
int value;
int lchild, rchild;
} b_tree[101];
int nn, seq[101], temp;
void in_order_traverse(int root) {
if (b_tree[root].lchild != -1) in_order_traverse(b_tree[root].lchild);
b_tree[root].value = seq[temp++];
if (b_tree[root].rchild != -1) in_order_traverse(b_tree[root].rchild);
}
void level_order_traverse(int root) {
queue mq;
mq.push(root);
while (!mq.empty()) {
int curr = mq.front();
mq.pop();
printf("%d", b_tree[curr].value);
temp--;
if (temp > 0) printf(" ");
if (b_tree[curr].lchild != -1) mq.push(b_tree[curr].lchild);
if (b_tree[curr].rchild != -1) mq.push(b_tree[curr].rchild);
}
}
int main() {
scanf("%d", &nn);
for (int i = 0; i < nn; ++i)
scanf("%d%d", &b_tree[i].lchild, &b_tree[i].rchild);
for (int i = 0; i < nn; ++i)
scanf("%d", &seq[i]);
sort(seq, seq + nn);
temp = 0;
in_order_traverse(0);
level_order_traverse(0); //BFS
return 0;
}