存在的问题:若根据先序遍历结果和中序遍历结果无法重建二叉树应该输出NO。但是它还做不到。
代码如下:
#include <stdio.h>
#include<iostream>
using namespace std;
typedef struct ListNode{
int value;
struct ListNode* pLeftChild;
struct ListNode* pRightChild;
}ListNode;
void lastSearch(ListNode *pHead)
{
if(pHead!=NULL)
{
if(pHead->pLeftChild!=NULL)
{
lastSearch(pHead->pLeftChild);
}
if(pHead->pRightChild!=NULL)
{
lastSearch(pHead->pRightChild);
}
printf("%c\n",pHead->value);
}
}
//if tag==1:rightChild。 if tag==0:leftChild
void reBuild(char* strPre,int preStrLength,char* strMid,int midStrLength,ListNode *node,int tag)
{
if(preStrLength<1 || midStrLength<1 || node==NULL || strPre==NULL || strMid==NULL || preStrLength!=midStrLength)
{
return;
}
int i;
char value=*strPre;
char *leftNewPreStr=(char *)malloc(preStrLength);
char *leftNewMidStr=(char *)malloc(midStrLength);
char *leftPre=leftNewPreStr;
char *leftMid=leftNewMidStr;
char *rightNewPreStr=(char *)malloc(preStrLength);
char *rightNewMidStr=(char *)malloc(midStrLength);
char *rightPre=rightNewPreStr;
char *rightMid=rightNewMidStr;
ListNode *newNode=(ListNode *)malloc(sizeof(ListNode));
newNode->value=value;
newNode->pLeftChild=NULL;
newNode->pRightChild=NULL;
if(tag)
{
node->pRightChild=newNode;
}else{
node->pLeftChild=newNode;
}
if(preStrLength==1)
{
return;
}
//在midStr中查找preStr第一个元素,以构建新的左子树mid序列
while(*strMid!=value){
*leftNewMidStr=*strMid;
leftNewMidStr++;
strMid++;
}
strMid++;
*leftNewMidStr='\0';
//printf("%s\n",leftMid);
//剩下的就是右子树的mid序列
while(*strMid!='\0'){
*rightNewMidStr=*strMid;
rightNewMidStr++;
strMid++;
}
*rightNewMidStr='\0';
//printf("%s\n",rightMid);
//构建左右子树的pre序列
strPre++;
for(i=0;i<strlen(leftMid);i++)
{
*leftNewPreStr=*strPre;
leftNewPreStr++;
strPre++;
}
*leftNewPreStr='\0';
//printf("%s\n",leftPre);
for(int i=0;i<=strlen(rightMid);i++)
{
*rightNewPreStr=*strPre;
rightNewPreStr++;
strPre++;
}
//printf("%s\n",rightPre);
//重建左子树
reBuild(leftPre,strlen(leftPre),leftMid,strlen(leftMid),newNode,0);
//重建右子树
reBuild(rightPre,strlen(rightPre),rightMid,strlen(rightMid),newNode,1);
}
int main()
{
char *preStr=(char *)malloc(sizeof(100));
char *midStr=(char *)malloc(sizeof(100));
ListNode *pHeader=(ListNode *)malloc(sizeof(ListNode));
pHeader->pLeftChild=NULL;
pHeader->pRightChild=NULL;
pHeader->value=-1;
gets(preStr);
gets(midStr);
reBuild(preStr,strlen(preStr),midStr,strlen(midStr),pHeader,0);
lastSearch(pHeader->pLeftChild);
system("pause");
return 0;
}