读书人

根据种序、前序求解后序,该怎么处理

发布时间: 2012-05-27 05:42:30 作者: rapoo

根据种序、前序,求解后序

C/C++ code
//节点struct node{node* lchild;node* rchild;int data;node():lchild(NULL),rchild(NULL){}node(int val):data(val),lchild(NULL),rchild(NULL){}};//完全二叉树class BiTree{    node* root;public:    BiTree():root(NULL){}    ~BiTree(){    Clear(); }        void Create(node* &tree, int a[], int len,int index)    //递归创建数    {        if(index>=len)            return;        tree=new node(a[index]);        Create(tree->lchild,a,len,2*index+1);        Create(tree->rchild,a,len,2*index+2);    }    void CreateTree(int a[], int len)    {        Create(root,a,len,0);    }};提供成员函数,根据中序,前序求解后序的函数。




[解决办法]
C/C++ code
typedef struct _BINARY_TREE_NODE_  {      char chValue;      struct _BINARY_TREE_NODE_ *Left,*Right;  }BTreeNode,*PBTree;      void RebuildBTree(const char* pPreOrder,const char* pInOrder,int nLen,PBTree& pRoot)  {      if (nLen==1)      {          pRoot = (BTreeNode*)malloc(sizeof(BTreeNode));          (pRoot)->chValue=pPreOrder[0];          (pRoot)->Left = NULL;          (pRoot)->Right = NULL;          return;      }      else      {          (pRoot) = (BTreeNode*)malloc(sizeof(BTreeNode));          (pRoot)->chValue=pPreOrder[0];          //search first char in InOrder          int i=0;          for (i=0;i<nLen;++i )          {              if(pInOrder[i]==pPreOrder[0])                  break;          }          if(i>0)              RebuildBTree(pPreOrder+1,pInOrder,i,((pRoot)->Left));          else              pRoot->Left= NULL;          if(i<nLen-1)              RebuildBTree(&(pPreOrder[i+1]),&(pInOrder[i+1]),nLen-i-1,((pRoot)->Right));          else              pRoot->Right=NULL;      }  }    void PreOr(PBTree pRoot)  {      if (pRoot)      {          printf(" %c ",pRoot->chValue);          PreOr(pRoot->Left);          PreOr(pRoot->Right);      }  }    void InOrder1(PBTree pRoot)  {      if(pRoot->Left)          InOrder1(pRoot->Left);      if(pRoot)          printf(" %c ",pRoot->chValue);      if (pRoot->Right)      {          InOrder1(pRoot->Right);      }  }    void Last(PBTree pRoot)  {      if(pRoot->Left)          Last(pRoot->Left);      if(pRoot->Right)          Last(pRoot->Right);            if(pRoot)          printf(" %c ",pRoot->chValue);  }      int main()  {      PBTree Root;      char Pre[]={"abdcef"};      char InOrder[]={"dbaecf"};      RebuildBTree(Pre,InOrder,6,Root);            printf("Previous Order\n");      PreOr(Root);      printf("\n");      printf("In Order\n");      InOrder1(Root);      printf("\n");      printf("Last Order\n");      Last(Root);      printf("\n");      return 0;  } 

读书人网 >C++

热点推荐