根據二叉樹的前序遍歷和中序遍歷構建二叉樹的c語言完整程式碼
阿新 • • 發佈:2019-01-31
//重建二叉樹:輸入某二叉樹的前序和中序遍歷,重建出該二叉樹 #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; }