前序——中序建樹

//指針變量在遞歸中不會改變

#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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章