7-4 中序遍历二叉树

按完全二叉树的层次遍历给出一棵二叉树的遍历序列(其中用0表示虚结点),要求输出该二叉树的深度及中序遍历该二叉树得到的序列。

输入格式:

首先输入一个整数T,表示测试数据的组数,然后是T组测试数据。每组测试数据首先输入一个正整数n(n≤1000),代表给出的二叉树的结点总数(当然,其中可能包含虚结点)。结点编号均为正整数,且各不相同。 然后输入n个正整数,表示按完全二叉树(即第1层1个结点,第2层2个,第3层4个,第4层有8个……)的层次遍历给出的二叉树遍历序列,如果某个结点不存在(虚结点),则以0代替。

输出格式:

对于每组测试,第一行输出中序遍历二叉树得到的序列(每两个数据之间留一个空格),第二行输出二叉树的深度。

输入样例:

2
1 1
4 1 4 0 2

输出样例:

1
1
2 4 1
3

代码:::::

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<string>
#include<map>
#include<vector>
#include<stack>
#include<set>
#include<bitset>
#include<cctype>
#include<list>
#include<queue>
using namespace std;

typedef struct tree {
	int data;
	struct tree* left;
	struct tree* right;
}Node;

int n, t, cnt, x, m, a[1010];
vector<int>c;
Node* root = NULL;

void Create_BinaryTree(Node*& q, int level, int h) {
	if (level == x + 1 || h > n) {
		q = NULL;
		return;
	}
	if (a[h] != 0) {
		q = (Node*)malloc(sizeof(Node));
		q->left = NULL;
		q->right = NULL;
		q->data = a[h];
		Create_BinaryTree(q->left, level + 1, 2 * h);
		Create_BinaryTree(q->right, level + 1, 2 * h + 1);
	}
	else {
		q = NULL;
	}
}

void In_BinaryTree(Node*& q) {
	if (q != NULL) {
		In_BinaryTree(q->left);
		cout << q->data;
		if (cnt-- != 1) {
			cout << " ";
		}
		In_BinaryTree(q->right);
		free(q);
	}

}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin >> t;
	while (t--) {
		cin >> n;
		x = 0;
		cnt = 0;
		m = n;
		while (m) {
			x++;
			m >>= 1;
		}
		for (int i = 1; i <= n; i++) {
			cin >> a[i];
			if (a[i] != 0) {
				cnt++;
			}
		}
		for (int i = 0; i < x; i++) {
			if (pow(2, i + 1) > n) {
				for (int j = pow(2, i); j <= n; j++) {
					c.push_back(a[j]);
				}
				if (count(c.begin(), c.end(), 0) == n - pow(2, i))
				{
					x = i+1;
					break;
				}
				c.clear();
			}
			else {
				for (int j = pow(2, i); j < pow(2, i + 1); j++) {
					c.push_back(a[j]);
				}
				if (count(c.begin(), c.end(), 0) == pow(2, i + 1) - pow(2, i))
				{
					x = i+1;
					break;
				}
				c.clear();
			}
		}
		Create_BinaryTree(root, 1, 1);
		In_BinaryTree(root);
		cout << endl << x << endl;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值