一.建树方法
1.儿子表示法
存储一个点的左右儿子,用r[]和l[]存一个点的左右儿子
2.顺序表示法
按顺序存储左右儿子,左儿子的编号是i * 2,右儿子编号是i * 2 + 1
因为按顺序存储,所以会有很多空节点,浪费空间
二.树的遍历
先序遍历
顺序:根-左-右
中序遍历
顺序:左-根-右
后序遍历
顺序:左-右-根
层序遍历
顺序:按层遍历
代码
void dfs(int u){
if(u==0){
return;//节点为空则结束
}
//这是先序遍历
//后序和中序只需要调换输出的位置
cout<<u; //输出根
dfs(l[u]);//找左儿子
dfs(r[u]);//找右儿子
return;
} 1.P1305 新二叉树
改装建树和遍历的代码即可
#include<bits/stdc++.h>
using namespace std;
int n;
int root;
int maxn=0;
int l[30],r[30];
void dfs(int u){
if(u==0)return;
cout<<char(u+'a'-1);
dfs(l[u]);
dfs(r[u]);
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>n;
for(int i=1;i<=n;i++){
string s;
cin>>s;
//我把字母转换为了数字,也可以直接存字符直接输出
if(i==1){
root=s[0]-'a'+1;
//记得找根,没找根30分
}
if(s[1]!='*'){
l[s[0]-'a'+1]=s[1]-'a'+1;
}
if(s[2]!='*'){
r[s[0]-'a'+1]=s[2]-'a'+1;
}
}
dfs(root);
return 0;
}2.[NOIP 2001 普及组] 求先序排列
难度算水黄
给出中序遍历和后序遍历,求先序遍历
用递归不断输出根,并拆分出中序遍历和后序遍历的左子树和右子树,即可得到先序遍历
AC代码
#include<bits/stdc++.h>
using namespace std;
void dfs(string back,string mid){
if(!mid.length())return;
int lens=back.length();
char root=back[lens-1];
int pos=mid.find(root);
cout<<root;//输出根
dfs(back.substr(0,pos),mid.substr(0,pos));//拆左子树
dfs(back.substr(pos,lens-pos-1),mid.substr(pos+1,lens-pos-1));//拆右子树
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
string a,b;
cin>>a>>b;
dfs(b,a);//注意调用dfs时不要调用反了
return 0;
}3.D4358 二叉树遍历(flist)
难度:黄
给出中序遍历和层序遍历,求先序遍历
循环遍历中序遍历和层序遍历,找到相同的即为根节点
再用中序遍历拆出左子树和右子树
AC代码
#include<bits/stdc++.h>
using namespace std;
void dfs(string zhong,string ceng){
int lenz=zhong.size();
int lenc=ceng.size();
for(int i=0;i<lenc;i++){
for(int j=0;j<lenz;j++){
if(ceng[i]==zhong[j]){
cout<<ceng[i];//输出节点
dfs(zhong.substr(0,j),ceng);//拆左子树
dfs(zhong.substr(j+1,lenz-j-1),ceng);//拆右子树
return;
}
}
}
return;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
string a,b;
cin>>a>>b;
dfs(a,b);
return 0;
}