二叉树有四种遍历方法
原图
struct tree{
int pretr,posttr;
int num;
}tr[107];遍历时注意事项
1. 先左后右
2. 四种遍历,没有好坏之分
3. 从根部遍历
dfs型遍历
1. 先序遍历
如图所示
在每个节点左上角做个标识,以根节点左上角为出发点,沿着树路径逆时针画个轮廓,以线先后经过的红点顺序记录节点值。
即为A -> B -> C -> D -> E -> F -> G -> H -> K
源代码
void preorder(int k){
if(k==0) return;
cout<<tr[k].num<<" ";
preorder(tr[k].pretr);
preorder(tr[k].posttr);
}2. 中序遍历
如图所示
以上述方法,即为 B -> D -> C -> A -> E -> H -> G -> K -> F
源代码
void inorder(int k){
if(k==0) return;
inorder(tr[k].pretr);
cout<<tr[k].num<<" ";
inorder(tr[k].posttr);
}3. 后序遍历
如图所示
即为 D -> C -> B -> H -> K -> G -> F -> E -> A
源代码
void postorder(int k){
if(k==0) return;
postorder(tr[k].pretr);
postorder(tr[k].posttr);
cout<<tr[k].num<<" ";
}bfs型遍历(共1个)
1. 层序遍历
如图所示

即为 A -> B -> E -> C -> F -> D -> G -> H -> K
源代码
void levelorder(int k){
queue<int> q;
q.push(k);
while(!q.empty()){
int now=q.front();
q.pop();
if(now==0) continue;
printf("%d ",tr[k].num);
q.push(tr[k].pre);
q.push(tr[k].post);
}
}