• poj2255


    重构二叉树,已知前序和中序,输出后序。

    #include <iostream>
    #include <cstring>
    using namespace std;

    struct treeNode
    {
     treeNode();
     char letter;
     treeNode* left;
     treeNode* right;
    };
    treeNode::treeNode()
    {
     left=NULL;
     right=NULL;
    }
    void AddNode(treeNode* node,bool left,bool right,char ch)
    {
     treeNode* tmpNode=new treeNode;
     tmpNode->letter=ch;

     if(true==left)
     {
      node->left=tmpNode;
     }
     else
     {
      node->right=tmpNode;
     }
    }
    int findSameLetter(char letter,char str[],int startPoint)
    {
     int len=0;
     for(int i=startPoint;str[i]!='/0';i++)
     {
      
      if(str[i]==letter)
      { 
       break;
      }
      len++;
      
     }
     return len;
    }
    void BuildTree(treeNode* cNode,char preStr[],char inStr[], int preStart,int inStart,int preEnd,int inEnd)
    {
     //把preStr[preStart]建立新的节点
     cNode->letter=preStr[preStart];
     //调用findSameStr[]找到左子树的共同字符串长度
     int len;
     len=findSameLetter(cNode->letter,inStr,inStart);
     if(len>0)//对左子树调用BuildTree  
     {
      cNode->left=new treeNode;
      BuildTree(cNode->left,preStr,inStr,preStart+1,inStart,preStart+len,inStart+len-1);
     }
     //对右子树调用BuildTree
     if(preStart+len+1<=preEnd)
     {
      cNode->right=new treeNode;
      BuildTree(cNode->right,preStr,inStr,preStart+len+1,inStart+len+1,preEnd,inEnd);
     }
    }
    void PostTravel(treeNode* node)
    {
     if(NULL!=node)
     {
      PostTravel(node->left);
      PostTravel(node->right);
      cout<<node->letter;
     }
     return;
    }
    int main()
    {
     char preStr[27];
     char inStr[27];
     int len;
     treeNode* rootNode=NULL;
     while(cin>>preStr>>inStr)
     {
      len=strlen(preStr)-1;
      rootNode=new treeNode;
      BuildTree(rootNode,preStr,inStr,0,0,len,len);
      PostTravel(rootNode);
      cout<<endl;
     }
     return 0;
    }

  • 相关阅读:
    IOS开发--第四阶段--关联
    1.7 Flask
    1.4 linux 路飞项目
    linux 1.3 nginx 负载均衡和配置文件
    1.2 redis
    1.1 xinnian
    12.30 linux 7
    12.29
    12.29 linux3 mysql和redis
    12.28 linux 第四天 安装python 和虚拟环境
  • 原文地址:https://www.cnblogs.com/bester/p/3255804.html
Copyright © 2020-2023  润新知