一.
先序遍历+中序遍历 以后序输出。
//由先序序列定义,此序列的第一个结点一定是二叉树的根。在中序序列里,此根结点左边的结点都是左子树的结点,而右边的结点都是右子树的结点。这样通过根结点,在中序序列中可以分离出:左子树的序列和右子树的序列。根据这两个序列,在先序序列中可以找到对应的左子序列和右子序列。在先序序列里左子序列的第一个结点是左子树的根,右子序列的第一个结点是右子树的根,这样就确定了二叉树的三个结点。同时,左右子树的根结点又可以分别把左右子序列划分成两个子序列。如此递归,当取尽先序序列中的结点时,就生成了一棵二叉树。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Node
{
union
{
char chData;
int iData;
}Data;
Node *pLeft;
Node *pRight;
};
Node* create(char *pPre, char *pIn, int iPre, int iInBegin, int iInEnd)
{
static int temp = iPre;
if (iInBegin >= iInEnd)
{
return NULL;
}
Node* root = new Node;
if (!root)
{
exit(1);
}
root->Data.chData = pPre[iPre];
root->pLeft = NULL;
root->pRight = NULL;
int i;
for (i = iInBegin; i < iInEnd; i++)
{
if (pIn[i] == pPre[iPre]) //在中序序列中找到根节点的值
{
break;
}
}
temp++;
root->pLeft = create(pPre, pIn, temp, iInBegin, i); //创建左子树
root->pRight = create(pPre, pIn, temp, i+1, iInEnd); //右子树
return root;
}
void postorder(Node* root)
{
if(root->pLeft)postorder(root->pLeft);
if(root->pRight)postorder(root->pRight);
printf("%c",root->Data.chData);
}
int main()
{
char pPre[10]="DBACEGF",pIn[10]="ABCDEFG";
int len;
Node* root;
len=strlen(pPre);
root=create(pPre,pIn,0,0,len);
postorder(root);
return 0;
}