需求:输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。
假设:该二叉树没有重复数字。
遍历二叉树的规律
在二叉树的前序遍历序列中,第一个数字总是树的根节点的值。
在中序遍历序列中,根节点的值在序列中间,左子树的节点的值位于根节点值的左边,而右子树的节点的值位于根节点的右边。
eg:
该二叉树如图:
根据前序遍历找到根节点,之后根据中序遍历确定该根节点的左子树和右子树
根据同样的原来就可以重建二叉树。
//声明二叉树节点
typedef struct node{
int data;//数据域
struct node *left;//记录左子女
struct node *right;//记录右子女
}BTNode;
重建二叉树
BTNode* constructCore(int *startPreOrder, int *endPreorder, int *startInorder, int *endInorder){
int rootValue = startPreOrder[0];//根据前序遍历,找到当前的根节点
//为根节点分配单元
BTNode *root = (BTNode*)malloc(sizeof(BTNode));
//初始化根节点
root->data = rootValue;
root->right = NULL;
root->left = NULL;
//如果当前二叉树只有(剩)一个节点
if (startPreOrder == endPreorder)
{
if (startInorder == endInorder&&*startInorder == *startPreOrder)
{
return root;
}
else{
printf("传入数据有误");
system("pause");
}
}
//在中序遍历表中找到根节点的值
int *rootInorder = startInorder;
while (rootInorder <= endInorder&&(*rootInorder != rootValue)){
rootInorder++;
}
if (rootInorder == endInorder&&*rootInorder!=rootValue)//在中序遍历中没有找到当前的根节点,数据有误
{
printf("在中序遍历中,没有找到目标根节点\n");
system("pause");
}
//计算左右子树的长度
int leftLength = rootInorder - startInorder;
//将当前的二叉树,分成三部分,根,左子树,右子树
int *leftPreOrderEnd = startPreOrder + leftLength;
if (leftLength > 0){
//构建左子树
root->left = constructCore(startPreOrder + 1, leftPreOrderEnd, startInorder, rootInorder - 1);
}
if(leftLength<endPreorder-startPreOrder){//如果总长度比左子树的长度大说明该二叉树有右子树
//构建右子树
root->right = constructCore(leftPreOrderEnd + 1, endPreorder, rootInorder + 1, endInorder);
}
return root;
}
初步判断,输入的序列是否合法。
BTNode* construct(int preorder[], int inorder[], int length){
//过滤不符合条件的序列
if (preorder == NULL||inorder == NULL||length <= 0){
return NULL;
}
return constructCore( preorder,preorder+length-1,inorder,inorder+length-1);
}
测试:
//前序遍历二叉树
void preOrder(BTNode *root){
if (root){
printf("%d ",root->data);
preOrder(root->left);
preOrder(root->right);
}
}
//中序遍历二叉树
void inOrder(BTNode *root){
if (root){
inOrder(root->left);
printf("%d ", root->data);
inOrder(root->right);
}
}
int main(void){
int preorder[8] = { 1, 2, 4, 7, 3, 5, 6, 8 };
int inorder[8] = { 4, 7, 2, 1, 5, 3, 8, 6 };
BTNode *root = construct(preorder, inorder, 8);
preOrder(root);
printf("\n\n");
inOrder(root);
system("pause");
return 0;
}
调试结果: