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 }

         

  • 相关阅读:
    LeetCode 225. 用队列实现栈 做题笔记
    杨辉三角
    字母图形
    01字符串
    圆的面积
    饮料和啤酒
    进制转换
    从今天起 复习算法
    乘法群
    Paillier同态加密的介绍以及c++实现
  • 原文地址:https://www.cnblogs.com/wzqstudy/p/9921682.html
Copyright © 2011-2022 走看看