问题 A 任意二叉树的层次遍历
有若干个节点,每个节点上都有编号,把这些节点随意地构成二叉树,请编程输出该二叉树的层次遍历序列。
输入:第一行是n(n小于100),表示有n个节点,每个节点按从1到n依次编号。第一行后有n行,每行三个正整数i、l、r,分别表示节点i及对应的左右孩子的编号,如果不存在孩子则以-1表示。三个整数之间用一个空格隔开。
输出:该二叉数的层次遍历序列。
样例输入:
4
1 2 4
3 1 -1
2 -1 -1
4 -1 -1
样例输出:
3 1 2 4
#include<iostream>
#include<stack>
#include<queue>
#include<string>
using namespace std;
struct node {
char a;
node* left;
node* right;
node() {
left = right = NULL; }
};
struct work {
int a, b, val;
};
node* convert(work* x, int a) {
node* p = new node;
p->a = x[a].val+'0';
if (x[a].a != -1) {
p->left = convert(x, x[a].a); }
if (x[a].b != -1) {
p->right = convert(x, x[a].b); }
return p;
}
class tree {
node* root;
public:
tree() {
root = new node; }
void create() {
int n; cin >> n; int r;
work* x = new work[n];
for (int i = 0; i < n; i++)
cin >> x[i].val >> x[i].a >> x[i].b;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (x[i].val == x[j].a) {
x[j].a = i;
break;
}
else if (x[i].val == x[j].b) {
x[j].b = i;
break;
}
if (j == n - 1)
r=i;
}
}
root = convert(x, r);
}
void qx(node *q) {
cout << q->a ;
if (q->left != NULL)qx(q->left);
if (q->right != NULL)qx(q->right);
}
void zx(node* q) {
if (q->left != NULL)zx(q->left);
cout << q->a;
if (q->right != NULL)zx(q->right);
}
void hx(node* q) <