矿业大学 2022数据结构实验三


问题 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) <
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值