前序——中序建树

来源:互联网 发布:未来国际局势知乎 编辑:程序博客网 时间:2024/06/07 00:55
//指针变量在递归中不会改变#include<stdio.h>#include<string.h>#include<stack>using namespace std;struct node{    char data;    node* lchild;    node* rchild;};char fd[100],sd[100];node* buildtree(int fds,int fde,int sds,int sde){      if(fds > fde)      {          return NULL;      }      char d = fd[fds];      int pos = sds;      while(sd[pos++] != d){}      --pos;      node* n = new node; // 一定要重新生成内存                                        //否则指针在递归循环中一直指向一个内存空间      n->data = fd[fds];      n->lchild = buildtree(fds+1,fds+pos-sds,sds,pos-1);      n->rchild = buildtree(fds+pos-sds+1,fde,pos+1,sde);      return n;}void visit_rootlast(node* root){    stack<node*> sta;    bool _end = false;    node* p;    node* mark = NULL;    sta.push(root);    while(!sta.empty())    {        p = sta.top();        while(p)        {               p = p->lchild;               sta.push(p);        }        mark = p;        sta.pop();        p = sta.top();        while(mark ==  p->rchild)        {            mark = sta.top();            sta.pop();            printf("%c",mark->data); // 访问根节点            if(sta.empty()) // 访问完根节点栈为空结束循环             {                 _end = true; // 虽然栈为空但是 p指针还是没有改变,后面还有将p->rchild压栈的操作                 break;             }            p = sta.top();        }        if(!_end)        {            p = p->rchild;            sta.push(p);        }    }    return ;}int main(){    scanf("%s%s",fd,sd);    int fde = strlen(fd)-1;    int sde = strlen(sd)-1;    node* root = buildtree(0,fde,0,sde);    visit_rootlast(root);    return 0;}

阅读全文
0 0