二叉树的三种遍历方式:
- 前序遍历:根 -> 左儿 -> 右儿
- 中序遍历: 左儿 -> 根 -> 右儿
- 后序遍历:左儿 -> 右儿 -> 根
//前序遍历
int r[];// 结点
void build(){
...}
void dfs(int u){
cout << r[u] << endl;
if(r[u<<1]) dfs(u<<1);
if(r[u<<1|1]) dfs(u<<1|1);
}
// 中序遍历
void dfs(int u){
if(r[u<<1]) dfs(u<<1);
cout << r[u] << endl;
if(r[u<<1|1]) dfs(u<<1|1);
}
// 后续遍历
void dfs(int u){
if(r[u<<1]) dfs(u<<1);
if(r[u<<1|1]) dfs(u<<1|1);
cout << r[u] << endl;
}
中序遍历序的一个应用
/*
author:@bzdhxs
date:2021/11/01
URL:https://codeforces.com/gym/102875/problem/C
*/
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<string>
using namespace std;
#define _orz ios::sync_with_stdio(false),cin.tie(0)
#define mem(str,num) memset(str,num,sizeof(str))
#define forr(i,a,b) for(int i = a; i <= b;i++)
using ll = long long;
using ull = unsigned long long;
const int inf = 0x3f3f3f3f;
const int N = 2e6;
int a[N];
int n;
void build(int i,int num){
a[i] = num;
if(num == 20) return;
build(i<<1,num+1);
build(i<<1|1,num+1);
}
void dfs(int u){
if(!n) return ;
if(a[u<<1]) dfs(u << 1);
if(n){
cout << a[u] <<" ";
n--;
}
if(a[u<<1|1]) dfs(u << 1|1);
}
void init(){
build(1,1);
dfs(1);
}
int main()
{
cin >> n;
init();
return 0;
}