1 BinaryTreeNode* ConstructCore(int* startPreorder,int* endPreorder,int* startInorder,int* endInorder) 2 { 3 //前序遍歷序列的第一個數字是根結點的值 4 int rootValue=startPreorder[0]; 5 BinaryTreeNode* root=new BinaryTreeNode(); 6 root->data=rootValue; 7 root->lchild=root->rchild=NULL; 8 9 if(startPreorder==endPreorder) 10 { 11 if(startInorder==endInorder&&*startPreorder==*startInorder) 12 return root; 13 else 14 throw exception("Invalid input."); 15 } 16 17 //在中序遍歷中找到根結點的值 18 int* rootInorder=startInorder; 19 while(rootInorder <= endInorder&&*rootInorder!=rootValue) 20 ++rootInorder; 21 if(rootInorder==endInorder&&*rootInorder!=rootValue) 22 throw exception("Invalid input."); 23 int leftLength=rootInorder-startInorder;//中序遍歷左子樹長度 24 int* leftPreorderEnd=startPreorder+leftLength; 25 if(leftLength>0) 26 { 27 //構建左子樹 28 root->lchild=ConstructCore(startPreorder+1,leftPreorderEnd,startInorder,rootInorder-1); 29 } 30 if(leftLength<endPreorder-startPreorder) 31 { 32 //構建右子樹 33 root->rchild=ConstructCore(leftPreorderEnd+1,endPreorder,rootInorder+1,endInorder); 34 } 35 return root; 36 } 37 38 BinaryTreeNode* Construct(int* preorder,int* inorder,int length)//由先序和中序重建二叉樹 39 { 40 if(preorder==NULL||inorder==NULL||length<=0) return NULL; 41 return ConstructCore(preorder,preorder+length-1,inorder,inorder+length-1); 42 }