L2-011 玩轉二叉樹

YuKiCheng發表於2024-03-31

和L2-006是一樣的。正常建樹,只是在BFS的時候先放右兒子。
L2-006 樹的遍歷 https://www.cnblogs.com/chengyiyuki/p/18106375
程式碼:

#include <bits/stdc++.h>
using namespace std;
const int N = 40;
int pre[N], in[N];
int L[N], R[N];
int build(int al, int ar, int bl, int br) {//先序 中序
	if (al > ar) return -1;
	int root = pre[al];
	int i;
	for (i = bl; i <= br; i++) {
		if (in[i] == root) break;
	}
	int Lsize = i - bl;
	int Rsize = br - i;
	L[root] = build(al + 1, al + Lsize, bl, i - 1);
	R[root] = build(al + Lsize + 1, ar, i+1, br);
	return root;
}
void BFS(int root) {
	queue<int> q;
	q.push(root);
	int flag = 0;
	while (!q.empty()) {
		int x =q.front();
		if (flag) cout << " ";
		cout << x;
		flag++;
		q.pop();
		if (R[x] != -1) q.push(R[x]);
		if (L[x] != -1) q.push(L[x]);
	}
}
int main() {
	int ssize;
	cin >> ssize;
	for (int i = 0; i < ssize; i++) {
		cin >> in[i];
	}
	for (int i = 0; i < ssize; i++) {
		cin >> pre[i];
	}
	int root = build(0, ssize - 1, 0, ssize - 1);
	BFS(root);
	return 0;
}

相關文章