//代码非原创,单纯做笔记便于复习
一、题目要求
给定一个一个树的先序和中序遍历结果,构建一棵树,并输出这棵树的层序遍历和后序遍历结果。注:这棵树的结点是由整数描述。
输入描述:
树结点总数m
先序输出序列
中序输出序列
输出描述:
层序输出序列
后序输出序列
二、代码
#include<bits/stdc++.h>
using namespace std;
const int maxn = 100010;
int n, preorder[maxn], inorder[maxn];
unordered_map<int, int> l,r,pos;
void build(int il, int ir, int pl, int pr){
int root = preorder[pl];
int k = pos[root];
if(il < k) build(il, k - 1, pl + 1, k - 1 - il + pl + 1);//左孩子
if(ir > k) build(k + 1, ir, k - 1 - il + pl + 1 + 1, pr);//右孩子
cout << root << " ";//根结点
}
int _build(int il, int ir, int pl, int pr){
int root = preorder[pl];
int k = pos[root];
if(il < k) l[root] = _build(il, k - 1, pl + 1, k - 1 - il + pl + 1);
if(ir > k) r[root] = _build(k + 1, ir, k - 1 - il + pl + 1 + 1, pr);
return root;
}
void bfs(int root){
queue<int> q;
q.push(root);
while(!q.empty()){
int t = q.front();
cout << t << " ";
q.pop();
if(l.count(t)) q.push(l[t]);
if(r.count(t)) q.push(r[t]);
}
}
int main(){
cin >> n;
for(int i = 0; i < n; i++) cin >> preorder[i];
for(int i = 0; i < n; i++){
cin >> inorder[i];
pos[inorder[i]] = i;
}
int root=_build(0,n-1,0,n-1);
bfs(root);
cout<<endl;
build(0, n - 1, 0, n - 1);
return 0;
}
三、代码图解
1.知识补充:
unordered_map:
定义:
unordered_map< key , value > m;
方法:
m.size();
m.insert(x); x 是pair
m.find(key);
m.count(key);
m.erase(key);
m[key] => value
#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
unordered_map<char,int> m;
m['a']=9;
m['?']=5;
m['z']=99;
m['A']=50;
m['Z']=-2;
m[' ']=0;
cout<<m.size()<<endl;
if(m.count(' ')==1)
{
cout<<m[' ']<<endl;
}
for(auto it=m.begin();it!=m.end();it++)
{
cout<<it->first<<" "<<it->second<<endl;
}
return 0;
}
2.代码解释
后序遍历:使用递归,按左右根的顺序访问输出。