输入某二叉树的前序和中序遍历结果,重建该二叉树

来源:互联网 发布:sql server union 用法 编辑:程序博客网 时间:2024/05/17 01:13
/*输入某二叉树的前序和中序遍历结果,重建该二叉树*/文中的前序遍历函数是为了验证重建的二叉树是否正确#include <iostream>using namespace std;struct tree{int value;tree *left;tree *right;};tree *constructCore(int *s1,int *e1,int *s2,int *e2){tree *root = new tree;root->value = s1[0];root->left = NULL;root->right = NULL;if (s1 == e1){if(s2 == e2 && *s1 == *s2)return root;}int  *p = s2;while(p<=e2 && *p!= s1[0]){p++;}int len_l = p-s2;int len_r = e2-p;int *new_e1 = s1+len_l;if(len_l>0){root->left = constructCore(s1+1,new_e1,s2,s2+len_l-1);}if (len_r>0){root->right = constructCore(new_e1+1,e1,p+1,e2);}return root;}tree *construct(int *pr,int *ino,int len){if (pr==NULL||ino==NULL||len<=0){return NULL;}return constructCore(pr,pr+len-1,ino,ino+len-1);}void pre(tree *root){if(root!=NULL){cout<<root->value<<endl;pre(root->left);pre(root->right);}}int main(){int s1[] = {1,2,4,7,3,5,6,8};int s2[] = {4,7,2,1,5,3,8,6};tree *root = construct(s1,s2,8);pre(root);return 0;}


0 0