玩转二叉树 (25 分)

玩转二叉树 (25 分)_第1张图片
思路: 根据中序和先序序列建树,然后层序输出(由于镜面反转,层序时先将右儿子节点加入队列,然后在将左儿子加入队列)

代码:

#include 
using namespace std;
const int N = 1e5 + 10; 
typedef long long LL; 
int n, cnt = 1;
int  midd[N], pre[N];
struct node
{
	int val, l, r;
}tr[N];

void build (int u, int l, int r)
{
	if (l == r)
	{
		tr[u].val = -1;
		return ;
	}
	int k = pre[cnt ++];
	tr[u] = {k, u * 2, u * 2 + 1};
	int mid = find (midd + 1, midd + 1 + n, k) - midd;
	//cout << "mid = " << mid << "\n";
	build (u * 2, l, mid);
	build (u * 2 + 1, mid + 1, r);
}
int main ()
{
	cin >> n;
	for (int i = 1; i <= n; i ++)	cin >> midd[i];
	for (int i = 1; i <= n; i ++)	cin >> pre[i];
	build (1, 1, n + 1);
		
	queue <int> q; 
	q.push (1);
	int flag = 0;
	while (q.size ())
	{
		auto t = q.front ();
		q.pop ();
		if (tr[t].val == -1) continue;
		if (!flag) cout << tr[t].val;
		else cout << " " << tr[t].val;
		flag ++;
		q.push (tr[t].r);
		q.push (tr[t].l); 
		
	}
	return 0;
	 
}

你可能感兴趣的:(算法,c++)