zoukankan      html  css  js  c++  java
  • 面试经典&&竞赛——二叉树

    To record her trees for future generations, she wrote down two strings for each tree: a preorder traversal (root, left subtree, right subtree) and an inorder traversal (left subtree, root, right subtree). For the tree drawn above the preorder traversal is DBACEGF and the inorder traversal is ABCDEFG. 
    She thought that such a pair of strings would give enough information to reconstruct the tree later (but she never tried it). 

    Now, years later, looking again at the strings, she realized that reconstructing the trees was indeed possible, but only because she never had used the same letter twice in the same tree. 
    However, doing the reconstruction by hand, soon turned out to be tedious. 
    So now she asks you to write a program that does the job for her! 

    题意:输入先序遍历,中序遍历,输出后序遍历。(看完之后如果不太理解可以看我下一篇随笔,后续我会更新具体思考过程)

    解题思路:1.首先需要根据先序遍历和中序遍历创建二叉树

         我们这里需要递归来实现,二叉树问题和递归联系非常紧密。

          BitTree *createBinTreeByPreIn(char *pre,char *in,int number);

          函数需要三个参数:先序遍历字符串(*pre),和中序遍历的字符串(*in),字符串个数(number)。

          结束条件:当字符串长度为0时结束;

     1 BitTree *createBinTreeByPreIn(char *pre,char *in,int number)
     2 {
     3     if(number==0)  return NULL;
     4     char c = pre[0];
     5     int i = 0;
     6     while(i<number && in[i]!=c)i++;
     7     int leftNumber = i;
     8     int rightNumber = number - i - 1;
     9     BitTree *node = (BitTree *)malloc(sizeof(BitTree));
    10     node->data = c;
    11     node->lchild = createBinTreeByPreIn(&pre[1],&in[0],leftNumber);
    12     node->rchild = createBinTreeByPreIn(&pre[leftNumber+1],&in[leftNumber+1],rightNumber);
    13     return node;
    14 }

         2.后续遍历二叉树

    1 void PostOrder(BitTree *bt)
    2 {
    3     if(bt!=NULL)
    4     {
    5         PostOrder(bt->lchild);
    6         PostOrder(bt->rchild);
    7         printf("%c",bt->data);
    8     }
    9 }

    最后加上主函数来测试我们的程序

     1 int main(int argc,char **argv)
     2 {
     3     char a[SIZE],b[SIZE];
     4     BitTree *p;
     5     while(scanf("%s%s",a,b)!=EOF)
     6     {
     7         p = createBinTreeByPreIn(a,b,strlen(a));
     8         PostOrder(p);
     9         printf("
    ");
    10     }
    11     return 0;
    12 }

         

  • 相关阅读:
    offsetLeft,Left,clientLeft的区别
    IIS 内部运行机制
    常用正则表达式
    千万不要把 bool 设计成函数参数
    ASP.NET第一课,IIS安装与配置
    将字符串转为变量名(C#)
    淘宝技术发展
    C# 反射机制
    技术普及帖:你刚才在淘宝上买了一件东西
    高性能分布式计算与存储系统设计概要——暨2012年工作3年半总结
  • 原文地址:https://www.cnblogs.com/wzqstudy/p/9921682.html
Copyright © 2011-2022 走看看