L2-006 樹的遍歷

YuKiCheng發表於2024-03-31

先建樹,然後遍歷陣列。
這種方式比較消耗空間,適用於資料量小的情況,如果形成一條鏈,那將是致命的這個空間。
方法一,陣列二叉樹

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int in[N], post[N];
vector<int> tree(N,-1); 
void build(int root, int start, int ed, int idx) {
	if (start > ed) return;
	int i;
	for (i = start; i <= ed; i++) {
		if (in[i] == post[root]) {
			break;
		}
	}
   tree[idx] = post[root];
	build(root - ed + i - 1, start, i - 1, 2 * idx);//左
	build(root - 1, i + 1, ed, 2 * idx + 1);//右
}
int main() {
	int ssize;
	cin >> ssize;
	for (int i = 0; i < ssize; i++) {
		cin >> post[i];
	}
	for (int i = 0; i < ssize; i++) {
		cin >> in[i];
	}
	build(ssize - 1, 0, ssize - 1, 1);
	int flag = 0;
	for (int i = 1; i < tree.size(); i++) {
		if (tree[i] != -1) {
           if(flag) cout << " ";
            cout << tree[i];
            flag++;
		}
	}
	return 0;
}

方法二,正常建樹+BFS

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

參考部落格: https://www.cnblogs.com/magicalzh/p/8659833.html

相關文章