二叉树
二叉树的定义
每个根只有两个分支:左儿子、右儿子
二叉树的遍历
前序遍历:按照根->左->右的顺序遍历
中序遍历:按照左->根->右的顺序遍历
后序遍历:按照左->右->根的顺序遍历
如上图,
二叉树的先序遍历为:
FBADCEGIH
二叉树的中序遍历为:
ABCDEFGHI
二叉树的后序遍历为:
ACEDBHIGF
给出一棵二叉树的先序/后序遍历以及中序遍历,求后序/先序遍历
1.给出先序、中序,求后序:(https://www.luogu.com.cn/problem/P1827)
示例代码:
#include<bits/stdc++.h>
using namespace std;
void DFS(string pre,string mid){
if(pre == "")return ;
int pos = mid.find(pre[0]);
char x = pre[0];
DFS(pre.substr(1,pos),mid.substr(0,pos));//遍历左儿子
DFS(pre.substr(pos+1),mid.substr(pos+1));//遍历右儿子
cout << x;//输出根
}
int main(){
string pre,mid;cin >> pre >> mid;//输入二叉树遍历
DFS(mid,pre);
return 0;
}2.给出后序、中序,求先序:https://www.luogu.com.cn/problem/P1030
示例代码:
#include<bits/stdc++.h>
#include<cstring>
using namespace std;
void DFS(string mid,string end){
if(end == "")return ;
int pos = mid.find(end[end.length()-1]);
char x = end[end.length()-1];
cout << x;//输出根
DFS(mid.substr(0,pos),end.substr(0,pos));//遍历左儿子
DFS(mid.substr(pos+1),end.substr(pos,end.length()-1-pos)); 遍历右儿子
}
int main(){
string mid,end;
cin >> mid >> end;//输入二叉树遍历
DFS(mid,end);
return 0;
}