PTA 7-10 樹的遍歷(二叉樹基礎、層序遍歷、STL初體驗之queue)


7-10 樹的遍歷(25 分)

給定一棵二叉樹的后序遍歷和中序遍歷,請你輸出其層序遍歷的序列。這里假設鍵值都是互不相等的正整數。

輸入格式:

輸入第一行給出一個正整數N30),是二叉樹中結點的個數。第二行給出其后序遍歷序列。第三行給出其中序遍歷序列。數字間以空格分隔。

輸出格式:

在一行中輸出該樹的層序遍歷的序列。數字間以1個空格分隔,行首尾不得有多余空格。

輸入樣例:

7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

輸出樣例:

4 1 6 3 5 7 2

其實build不出來return 0會比較好,memset也全化為0,可以稍微簡化一下代碼

從build里面可以學會:表示兩個元素一樣,順序卻不一樣(又不能打亂它的順序)的集合的時候,可以試着用元素個數表示。

認真看代碼,學會里面的一萬種技巧。

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<set>
#include<queue>
typedef long long ll;
using namespace std;
const int maxn = 100 + 10;
int post[maxn], in[maxn];
int rch[maxn], lch[maxn];
int build(int l1, int r1, int l2, int r2){//post[l1...r1],in[l2...r2]
    if(l1 > r1 || l2 > r2) return -1;
	int root = post[r1];
	int p = 0;
	while(in[l2+p] != root) p++;//p為左子樹節點個數
	lch[root]=build(l1,l1+p-1 ,l2, l2+p-1);//建立左子樹 
	rch[root]=build(l1+p, r1-1, l2+p+1, r2);//建立右子樹 
	return root;
}
void bfs(int root){
	queue<int>q;
	q.push(root);
	while(!q.empty()){
		int tn = q.front();
		printf("%d", tn);
		q.pop();
		if(lch[tn] > 0){
			q.push(lch[tn]);
		}
		if(rch[tn] > 0){
			q.push(rch[tn]);
		}
		if(q.size()!= 0) printf(" ");
	}
	return;
}

int main(){
    int n;
    scanf("%d", &n);
    memset(rch, -1, sizeof(rch));
    memset(lch, -1, sizeof(lch));
    for(int i = 0; i < n; i++)scanf("%d", &post[i]);
    for(int i = 0; i < n; i++)scanf("%d", &in[i]);
    int root = build(0, n-1,0 , n-1);
    //for(int i = 1; i <= n; i++) printf("lch[%d] = %d, rch[%d] = %d\n", i, lch[i], i, rch[i]);
    bfs(root);
   
    return 0;
}



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM