#include<iostream> using namespace std; struct Node { char value; Node *left; Node *right; }; //重构函数核心 Node *Constructcore(char *start_preorder,char *end_preorder,char *start_inorder,char *end_inorder) { char rootvalue=start_preorder[0]; Node *root=new Node; root->value=rootvalue; root->left=root->right=NULL; if(start_preorder==end_preorder) { if(start_inorder==end_inorder&&*start_inorder==*start_preorder) { return root; } else throw std::exception("invalid inout"); } //下面开始在中序遍历中找到根节点的值 char *rootinorder=start_inorder; while(rootinorder<end_inorder&&*rootinorder!=rootvalue) { rootinorder++; } if(rootinorder==end_inorder&&*rootinorder!=rootvalue) { throw std::exception("invalid input"); } int left_length=rootinorder-start_inorder; char *left_preorder_end=start_preorder+left_length; if(left_length>0) { root->left=Constructcore(start_preorder+1,left_preorder_end,start_inorder,rootinorder-1); } if(left_length<end_preorder-start_preorder) { root->right=Constructcore(left_preorder_end+1,end_preorder,rootinorder+1,end_inorder); } return root; } //重构函数 Node *construct(char *preorder,char *inorder,int length) { if(preorder==NULL||inorder==NULL||length<=0) return NULL; return Constructcore(preorder,preorder+length-1,inorder,inorder+length-1); } void inorder_(Node *node) { if(node==NULL) return ; cout<<node->value<<" "; inorder_(node->left); inorder_(node->right); } int main() { char preorder[6]={'a','b','d','c','e','f'}; char inorder[6]={'d','b','a','e','c','f'}; Node *root=construct(preorder,inorder,6); inorder_(root); cout<<endl; system("pause"); return 0; }
时间: 2024-10-17 12:29:18