您的位置:首页 > 其它

题目7:重建二叉树

2018-03-16 17:05 274 查看
    题目:输入二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如,输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建如下图构建的二叉树并输出的它的头结点。

代码如下:#include<stdio.h>
#include<stdlib.h>

typedef struct BinaryTreeNode{
int value;
BinaryTreeNode* Left;
BinaryTreeNode* Right;
}*TreeNode;

TreeNode ConstructCore(int* startpreorder,int* endpreorder,int* startinorder,int* endinorder);
TreeNode 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);

}
TreeNode ConstructCore(int* startpreorder,int* endpreorder,int* startinorder,int* endinorder){

//前序遍历序列的第一个数字是根节点的值
int rootValue = startpreorder[0];
TreeNode root = (TreeNode)malloc(sizeof(BinaryTreeNode));
root->value = rootValue;
root->Left=root->Right=NULL;

if(startpreorder==endpreorder){
if(startinorder==endinorder&&*startpreorder==*startinorder)
return root;
else
printf("无效输入!");

}

//在中序遍历序列中找到根节点的值
int* rootinorder = startinorder;
while(rootinorder<=endinorder&&*rootinorder!=rootValue)rootinorder++;
if(rootinorder==endinorder&&*rootinorder!=rootValue)
printf("无效输入!");
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;
}

int main(){
int length = 7;
int preorder[7] = {1, 2, 4, 5, 3, 6, 7};
int inorder[7] = {4, 2, 5, 1, 6, 3, 7};
construct(preorder,inorder,length);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: