zoukankan      html  css  js  c++  java
  • 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;
    }

  • 相关阅读:
    js作用域链
    函数声明提升
    18年年终总结之谈谈焦虑这件事
    混合开发中ios兼容问题
    vue 缓存的keepalive页面刷新数据
    vue里监听安卓的物理返回键
    vue根据数组对象中某个唯一标识去重
    Sublime Text3 插件
    全面理解Javascript闭包和闭包的几种写法及用途
    javascript深入理解js闭包
  • 原文地址:https://www.cnblogs.com/bester/p/3255804.html
Copyright © 2011-2022 走看看