zoukankan      html  css  js  c++  java
  • 二叉树遍历

    题目描述:
    二叉树的前序、中序、后序遍历的定义:
    前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树;
    中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树;
    后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。
    给定一棵二叉树的前序遍历和中序遍历,求其后序遍历(提示:给定前序遍历与中序遍历能够唯一确定后序遍历)。
    输入:
    两个字符串,其长度n均小于等于26。
    第一行为前序遍历,第二行为中序遍历。
    二叉树中的结点名称以大写字母表示:A,B,C....最多26个结点。
    输出:
    输入样例可能有多组,对于每组测试样例,
    输出一行,为后序遍历的字符串。
    样例输入:
    ABC BAC FDXEAG XDEFAG
    样例输出:
    BCA XEDGAF
     
    #include<iostream>
    #include<stdio.h>
    #include<string.h>
    using namespace std;
     
    struct node {
        node *lchild;
        node *rchild;
        char c;
    }tree[50];
     
    int loc;
     
    node* creat(){
        tree[loc].lchild = tree[loc].rchild = NULL;
        loc++;
        return &tree[loc-1];
    }
    char str1[30],str2[30];
    void post(node *t){
        if (t->lchild){
            post(t->lchild);
        }
        if (t->rchild){
            post(t->rchild);
        }
        printf ("%c",t->c);
    }
    node * build (int s1,int e1,int s2,int e2){
        node * ret=creat();
        ret->c=str1[s1];
        int rootidx;
        for (int i=s2;i<=e2;i++){
            if (str2[i] == str1[s1]){
                rootidx = i;
                break;
            }
        }
        if (rootidx != s2){
            ret->lchild = build(s1+1,s1+rootidx-s2,s2,rootidx-1);
        }
        if (rootidx != e2){
            ret->rchild = build(s1+rootidx-s2+1,e1,rootidx+1,e2);
        }
        return ret;
    }
     
    int main(){
        while (scanf("%s",str1)!=EOF){
            scanf("%s",str2);
            loc=0;
            int l1=strlen (str1);
            int l2=strlen (str2);
            node * t=build (0,l1-1,0,l2-1);
            post(t);
            cout<<endl;
        }
         
        return 0;
    }
     
     
  • 相关阅读:
    用 ArcMap 发布 ArcGIS Server FeatureServer Feature Access 服务 PostgreSQL 版本
    ArcMap 发布 ArcGIS Server OGC(WMSServer,MapServer)服务
    ArcScene 创建三维模型数据
    ArcMap 导入自定义样式Symbols
    ArcMap 导入 CGCS2000 线段数据
    ArcMap 导入 CGCS2000 点坐标数据
    ArcGis Server manager 忘记用户名和密码
    The view or its master was not found or no view engine supports the searched locations
    python小记(3)操作文件
    pytest(2) pytest与unittest的区别
  • 原文地址:https://www.cnblogs.com/yexiaoqi/p/7221986.html
Copyright © 2011-2022 走看看