• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
村雨sup
自己选的路,跪着也要走完 XD
博客园    首页    新随笔    联系   管理    订阅  订阅
二叉树遍历
#include <bits/stdc++.h>
using namespace std;

struct Node{
    int m;
    int l;
    int r;
}node[100];

void first(int k){
    cout << node[k].m << " ";
    if(node[k].l != 0)first(node[k].l);
    if(node[k].r != 0)first(node[k].r);
}
void middle(int k){
    if(node[k].l != 0)middle(node[k].l);
    cout << node[k].m << " ";
    if(node[k].r != 0)middle(node[k].r);
}
void last(int k){
    if(node[k].l != 0)last(node[k].l);
    if(node[k].r != 0)last(node[k].r);
    cout << node[k].m << " ";
}

int main(){
    int n;
    cin >> n;
    for(int i = 1;i <= n;i++){
        cin >> node[i].l >> node[i].r;
        node[i].m = i;
    }
    first(1); cout << endl;
    middle(1); cout << endl;
    last(1);

}

前序、中序、后序 遍历 其实蛮简单的注意下位置就行了

posted on 2017-10-28 00:19  村雨sup  阅读(189)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3