树

· · 个人记录

二叉树

二叉树的定义

每个根只有两个分支:左儿子、右儿子

二叉树的遍历

前序遍历:按照根->左->右的顺序遍历

中序遍历:按照左->根->右的顺序遍历

后序遍历:按照左->右->根的顺序遍历

(https://img-blog.csdnimg.cn/20210228151732391.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzM3ODcyMjE2,size_16,color_FFFFFF,t_70#pic_center)

如上图,

二叉树的先序遍历为:

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;
}