二叉树的探索 poj 2255

来源:互联网 发布:应用数学知乎 编辑:程序博客网 时间:2024/05/17 23:57

第一次接触真正意义上的算法:二叉树;

poj 2255:

已知前根序列,中根序列,求后根序列;

刚开始思路:

完全不会,上网搜代码;

网上书本上找资料,终于看懂代码,并写下注释


  1. #include<iostream>#include<cstdio>  #include<string>  using namespace std;   struct Node//定义一棵树// {      char data;      Node * lchild; //指针指向左子树    Node * rchild;  //指针指向右子树};   Node* CreatTree(string pre, string in)  //建立一棵树{      Node * root = NULL;  //树的初始化  :定义指针为空    if(pre.length() > 0)  //判定是否有字符串输入 :字符串的长度大于0    {          root = new Node;  //为根结点申请结构体所需要的内存          root->data = pre[0]; //先序序列的第一个元素为根结点  :指针指向data初始化为pre字符串的第一个字符        int index = in.find(root->data);  //查找中序序列中的根结点位置  :找出这个字符在in中的位置;        root->lchild = CreatTree(pre.substr(1, index), in.substr(0, index));  //递归创建左子树  :把原字符串分为两部分,递归        root->rchild = CreatTree(pre.substr(index + 1), in.substr(index + 1)); //递归创建右子树      }      return root;  }   void PostOrder(Node * root)  //递归后序遍历  :LRD{       if(root != NULL) //递归判定    {          PostOrder(root->lchild);  //L        PostOrder(root->rchild);  //R        cout<<root->data;  //输出    }  }   int main()  //主程序{      string pre_str, in_str;      Node *root; //定义根指针    while(cin>>pre_str>>in_str)//输入字符串      {          root = CreatTree(pre_str, in_str);//根据前序和中序建立二叉树          PostOrder(root);  //输出后序遍历        cout<<endl;      }      return 0;  }

    然后开始编写自己的程序,中间发现了很多的问题:
  1.  指向函数的指针感觉自己用的不是很好,然后就是关于递归函数的编写,感觉自己不试运行下就不对 的样子。
  2. 思路有的时候不是很清晰。
  3. 基本就是这些,下次继续努力~~
  4. 最后贴出自己的代码:
  5. #include<iostream> #include<cstdio>  #include<string>  using namespace std;    struct node{       char data;       node *l;       node *r;      };node *creat(string qian,string zhong ){         node*root=NULL;     if(qian.length()>0){     root=new node;     root->data=qian[0];     int index=zhong.find(root->data);     root->l=creat(qian.substr(1,index),zhong.substr(0,index));     root->r=creat(qian.substr(index+1),zhong.substr(index+1));     }     return root;}void hou(node *root){     if(root!=0){     hou(root->l);     hou(root->r);     cout<<root->data;     }     }int main(){    string pre,in;    node *root;    while(cin>>pre>>in){                        root=creat(pre,in);                        hou(root);                        cout<<endl;                        }                        return 0;                        }     



原创粉丝点击