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 }

         

  • 相关阅读:
    解决vs code 内置终端,字体间隔过大问题。(linux centos7 ubuntu成功)
    安装Epson打印机但因lsb依赖错误而中断的驱动程序
    ubuntu 权限不够,解决办法,无法获得锁 /var/lib/dpkg/lock
    ubuntu 安装WPS
    GNU GRUB引导的默认启动项是ubuntu
    网络编程基础
    反射、特殊双下方法、单例模式
    异常处理
    封装、多态、类的约束、类的私有成员
    多继承、经典类与新式类、新式类的C3算法详解
  • 原文地址:https://www.cnblogs.com/wzqstudy/p/9921682.html
Copyright © 2011-2022 走看看