已知二叉樹的兩種遍歷求另一種遍歷(C++程序實現)

//給定一棵二叉樹的前序遍歷和中序遍歷,求其後序遍歷

#include <iostream>
#include <string.h>
using namespace std;

typedef struct BinTree
{
    char data;
    BinTree* lchild;
    BinTree* rchild;
} BinTree;

void RebuildTree(BinTree* &Tree,char *pre,char *in,int len)
{
    Tree = new BinTree;
    if(Tree!=NULL)
    {
        if(len<=0)//遞歸截止條件
        {
            Tree = NULL;
            return ;
        }
        int index = 0;
        while(index<len&&*(pre)!=*(in+index))
        {
            //尋找當前的root結點(包含子樹)
            index++;
        }
        Tree->data = *(pre);
        RebuildTree(Tree->lchild,pre+1,in,index);//去掉root結點
        RebuildTree(Tree->rchild,pre+1+index,in+1+index,len-(index+1));//去掉左邊和根節點
    }
    return ;
}

void PostOrderTravese(BinTree* Tree)
{
    //後序遍歷輸出
    if(Tree==NULL)
        return;
    PostOrderTravese(Tree->lchild);
    PostOrderTravese(Tree->rchild);
    cout<<Tree->data<<" ";
}


int main()
{
    char pre[101];  //string pre;
    char in[101];   //string in;
    cout<<"Inuput DLR and LDR:"<<endl;
    while(cin>>pre>>in)
    {
        BinTree* tree;
        int length = strlen(pre);
        RebuildTree(tree,pre,in,length);
        PostOrderTravese(tree);
        cout<<endl;
    }
    return 0;
}


//給定一棵二叉樹的中序序遍歷和後序遍歷,求其後序遍歷
#include<iostream>
using namespace std;
typedef struct _btn{
    int data;
    struct _btn *lchild;
    struct _btn *rchild;
}btn;
#define MAXN 65536
int inOrder [MAXN];
int postOrder [MAXN];
btn *buildtree(int io1,int io2,int po1,int po2)//中序的首尾元素座標,後序的首尾元素座標
{
    int iolen=io2-io1+1;//中序的長度
    int i;
    btn *root=new btn;//新建的一個結點作爲根結點
    root->data=postOrder[po2];//後序的最後一個元素是根結點
    root->lchild=NULL;
    root->rchild=NULL;//左右孩子初始化爲空
    //在中序裏尋找根結點
    for(i=0;i<iolen;++i)
    {
        if(root->data==inOrder[io1+i])
        break;
     }
     //於是左子樹的中序從io1到io1+i-1,後序從po1到po1+i-1
     //注意遞歸出口,只有當io1<=io1+i-1即i>=1時纔有意義
      if(i>=1)
      root->lchild=buildtree(io1,io1+i-1,po1,po1+i-1);
      //右子樹類似
      if(io1+i+1<=io2)
      root->rchild=buildtree(io1+i+1,io2,po1+i,po2-1);
      //返回根結點
      return root;
}
void preOrder(btn *root)
{
    if(root!=NULL)
    {
        cout<<root->data<<" ";
        preOrder(root->lchild);
        preOrder(root->rchild);
    }
}
//後序遍歷,用於釋放二叉樹
void deletetree(btn *root)
{
    if(root!=NULL)
    {
        deletetree(root->lchild);
        deletetree(root->rchild);
        delete root;
        root=NULL;
    }
 }
 int main()
 {
    int i=0;
    while(cin>>inOrder[i++])
    {
        if(cin.get()!=' ')
        break;
     }
  i=0;
  while(cin>>postOrder[i++])
  {
    if(cin.get()!=' ')
    break;
  }
  btn *root=buildtree(0,i-1,0,i-1);
  preOrder(root);
  deletetree(root);
  return 0;
}

 

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