#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
struct Node {
int data;
Node *lchild, *rchild;
Node () {
lchild = rchild = NULL;
}
};
void Build(Node *&T, int u, int arr[], int len) { // T是指针的引用
if (u > len || arr[u] == -1) {
return;
}
T = new Node();
T->data = arr[u];
Build(T->lchild, u*2, arr, len);
Build(T->rchild, u*2+1, arr, len);
}
void Bfs(Node *T) { // 层序遍历
queue<Node*> Q;
Q.push(T);
while (!Q.empty()) {
Node *t = Q.front();Q.pop();
printf("%d ", t->data);
if (t->lchild != NULL) Q.push(t->lchild);
if (t->rchild != NULL) Q.push(t->rchild);
}
}
void PreOrder(Node *T) {
if (T == NULL) return;
printf("%d ", T->data); // 先根
PreOrder(T->lchild);
PreOrder(T->rchild);
}
int main() {
int a[100], n = 10;
Node *root;
for (int i=1;i<=n;i++) {
a[i] = i;
}
// a[3] = -1; // -1表示空
Build(root, 1, a, n);
Bfs(root);
// PreOrder(root);
return 0;
}
通过数组构建二叉树&遍历
最新推荐文章于 2022-05-31 23:07:18 发布