zoukankan      html  css  js  c++  java
  • [笔记]: 二叉树 遍历转换 标签: 二叉树遍历 2017-05-16 19:55 36人阅读 评论(0) 收藏

    遍历命名
    根据访问结点操作发生位置命名:
    ① NLR:前序遍历(Preorder Traversal 亦称(先序遍历))
    ——访问根结点的操作发生在遍历其左右子树之前。
    (中 左 右)
    ② LNR:中序遍历(Inorder Traversal)
    ——访问根结点的操作发生在遍历其左右子树之中(间)。
    (左 中 右)
    ③ LRN:后序遍历(Postorder Traversal)
    ——访问根结点的操作发生在遍历其左右子树之后。
    (左 右 中)

    1. 先,中序遍历转后序遍历
    如:DBACEGF ABCDEFG
    输出 ACBFGED

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<cstdlib>
    #include<algorithm>
    #include<cmath>
    using namespace  std;
    void solve(char *s,char *t){
        int i,k;
        char t2[100],s2[100];
        if(strlen(s)==1) printf("%s",s);
        else
        {
            k=strchr(t,s[0])-t;//找到根节点 
            if(k>0){//左子树
                strncpy(t2,t,k);
                t2[k]='';
                strncpy(s2,s+1,k);
                s2[k]='';
                solve(s2,t2);
            } 
            if(k<strlen(t)-1){//右子树
                strncpy(t2,t+k+1,strlen(t)-k-1);
                t2[strlen(t)-k-1]='';
                strncpy(s2,s+k+1,strlen(s)-k-1);
                t2[strlen(s)-k-1]='';
                solve(s2,t2);
            }
            printf("%c",t[k]);
        } 
    }
    int main(){
        char a[100],b[100];
        scanf("%s",a);
        scanf("%s",b);
        solve(a,b);
        return 0;
    }
    

    2.后,中续转先序

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<cstdlib>
    #include<algorithm>
    #include<cmath>
    using namespace  std;
    void solve(char *s,char *t){
        int i,k;
        char t2[100],s2[100];
        if(strlen(s)==1) printf("%s",s);
        else
        {
            k=strchr(t,s[0])-t;
            if(k>0){
                strncpy(t2,t,k);
                t2[k]='';
                strncpy(s2,s+1,k);
                s2[k]='';
                solve(s2,t2);
            } 
            if(k<strlen(t)-1){
                strncpy(t2,t+k+1,strlen(t)-k-1);
                t2[strlen(t)-k-1]='';
                strncpy(s2,s+k+1,strlen(s)-k-1);
                t2[strlen(s)-k-1]='';
                solve(s2,t2);
            }
            printf("%c",t[k]);
        } 
    }
    int main(){
        char a[100],b[100];
        scanf("%s",a);
        scanf("%s",b);
        solve(a,b);
        return 0;
    }
    
  • 相关阅读:
    基于React 的audio音频播放组件
    React Context 的基本用法
    Video-React 视频播放组件的使用
    Html5 Canvas 使用
    React 中使用富文本编辑器 Braft Editor ,并集成上传图片功能
    ant design pro 项目实现路由级的动态加载按需加载
    确保代码仓库中包含 yarn.lock 文件
    ES6 对象解构赋值(浅拷贝 VS 深拷贝)
    JS 中判断数据类型是否为 null、undefined 或 NaN
    js中的数据类型及判断方法
  • 原文地址:https://www.cnblogs.com/xljxlj/p/7183657.html
Copyright © 2011-2022 走看看