1. 程式人生 > >根據前序遍歷序列和中序遍歷序列構造二叉樹演算法

根據前序遍歷序列和中序遍歷序列構造二叉樹演算法

http://blog.csdn.net/yunzhongguwu005/article/details/9270085
 1 確定根,確定左子樹,確定右子樹
 2 在左子樹中遞迴
 3 在右子樹中遞迴
 4 列印當前根
I 前序遍歷的第一個就是根。
II 中序遍歷根據根,分成左子樹和右子樹。
III 重複I步
#include <iostream>
#include <string>
#include "stdlib.h"


using namespace std;


typedef struct BiNode
{
  char data;
  struct BiNode *lchild;
  struct BiNode *rchild;
}BiNode,*BiTree;


void CreateBiTree(BiTree&t, string presequence,string insequence)
{
  //it is leaf
  if (presequence.length()==0)
  {
    t=NULL;
    return ;
  } 
  //root
  char rootNode=presequence[0];
  //root location in inorder
  int index=insequence.find(rootNode);
  //left child sequence
  string lchild_insequence=insequence.substr(0,index);
  //right chlid sequence
  string rchild_insequence=insequence.substr(index+1);
  //left child length
  int lchild_length=lchild_insequence.length();
  //right child length
  int rchild_length=rchild_insequence.length();
  //left child presequence
  string lchild_presequence=presequence.substr(1,lchild_length);
  //right child presequence
  string rchild_presequence=presequence.substr(1+lchild_length);


  t=(BiTree)malloc(sizeof(BiNode));
  if (t!=NULL)
  { 
    t->data=rootNode;
    CreateBiTree(t->lchild,lchild_presequence,lchild_insequence);
    CreateBiTree(t->rchild,rchild_presequence,rchild_insequence);
  }
}


void  PreOrderTraverse(BiTree&t)
{
  if (t!=NULL)
  {
    cout<<t->data;
    PreOrderTraverse(t->lchild);
    PreOrderTraverse(t->rchild);
  }
}


void InOrderTraverse(BiTree&t)
{
  if (t!=NULL)
  {
    InOrderTraverse(t->lchild);
    cout<<t->data;
    InOrderTraverse(t->rchild);
  }
}


main()
{
  BiTree t;
  string presequence="ABCDEFG";
  string insequence="CBEDAFG";;
  


  CreateBiTree(t,presequence,insequence);
 
  PreOrderTraverse(t);
  cout<<endl;
  InOrderTraverse(t);
  getchar();
  
   return 0;
}