二叉树
二叉树
二叉树 blog
遍历
B3642 二叉树的遍历
#include<bits/stdc++.h>
using namespace std ;
const int N = 1e6 + 10 ;
struct xx{
int l , r ;
}a[N];
void bl(int b, int v){
if(b == 1) cout << v << " " ; //先序遍历
if(a[v].l != 0) bl(b , a[v].l) ;
if(b == 2) cout << v << " " ; //中序遍历
if(a[v].r != 0) bl(b , a[v].r) ;
if(b == 3) cout << v << " " ; //后序遍历
}
int main(){
int n ;
cin >> n ;
for( int i = 1 ; i <= n ; i++ ){
cin >> a[i].l >> a[i].r ;
}
for( int i = 1 ; i <= 3 ; i++ ){
bl(i , 1) ;
cout << endl ;
}
return 0 ;
}
简化
先序遍历和中序遍历序列,输出它的后序遍历序列
#include<bits/stdc++.h>
using namespace std ;
string xx , zx ;
int len ;
void hx(int zBegin , int zEnd , int xBegin , int xEnd){
for( int i = zBegin ; i <= zEnd ; i++ ){
if(zx[i] == xx[xBegin]){
hx(zBegin , i - 1 , xBegin + 1 , xBegin - zBegin + i) ;
hx(i + 1 , zEnd , xBegin - zBegin + i + 1 , xEnd) ;
cout << xx[xBegin] ;
}
}
}
int main(){
while(cin >> xx >> zx){
len = xx.size() ;
hx(0 , len - 1 , 0 , len - 1) ;
cout << endl ;
}
return 0 ;
}
好记
#include<stds/stdc++.h>
using namespace std ;
string zx , xx ;
void hx(string s1 , string s2){
char root = s1[0] ;
int l = s2.find(root) ;
int r = s2.size() - l - 1 ;
if(l){
string x = s1.substr(1 , l) ;
string z = s2.substr(0 , l) ;
hx(x , z) ;
}
if(r){
string x = s1.substr(l+1 , r) ;
string z = s2.substr(l+1 , r) ;
hx(x , z) ;
}
cout << root ;
}
int main(){
while(cin >> xx >> zx){
hx(xx , zx) ;
cout << endl ;
}
return 0 ;
}