根据二叉树的前序遍历和中序遍历构建二叉树的c语言完整代码
2016-04-26 17:22
525 查看
//重建二叉树:输入某二叉树的前序和中序遍历,重建出该二叉树 #include<stdio.h> #include<malloc.h> typedef struct binarytreenode { int value; struct binarytreenode *left; struct binarytreenode *right; }binary; binary* constructcore(int *startpreorder,int *endpreorder,int *startinorder,int *endinorder) { int *rootinorder=NULL; int leftlength =0; //左子树的长度 int * leftpreend =NULL; //前序遍历中左子树的终结点 int rootvalue=startpreorder[0]; //前序遍历中的第一个结点的值便是根节点的值 binary *root = malloc(sizeof(binary)); root->value=rootvalue; root->left=root->right=NULL; if(startpreorder==endpreorder) { if(startinorder==endinorder&& *startpreorder==*startinorder) //前序遍历和中序遍历中都只有根节点的情况 return root; else printf("invalid input\n"); // return root; } //在中序遍历中找到根节点的值 rootinorder = startinorder; while(rootinorder<=endinorder&& *rootinorder != rootvalue) { ++rootinorder; } if(rootinorder==endinorder&& *rootinorder != rootvalue) printf("invalid input"); leftlength = rootinorder-startinorder; leftpreend = startpreorder + leftlength; if(leftlength>0) { root->left = constructcore(startpreorder+1,leftpreend,startinorder,rootinorder-1); //构建左子树 } if(leftlength < endpreorder-startpreorder) { root->right = constructcore(leftpreend+1,endpreorder,rootinorder+1,endinorder); } return root; } binary *construct(int *preorder,int *inorder,int length) { if(preorder==NULL||inorder==NULL||length<=0) return NULL; else return constructcore(preorder,preorder+length-1,inorder,inorder+length-1); } int main() { int preorder[]={1,2,4,7,3,5,6,8}; int inorder[]={4,7,2,9,5,3,8,6}; binary *root; root=construct(preorder,inorder,8); printf("%d\n",root->value); return 0; }