您的位置:首页 > 其它

中序后序确定二叉树的前序序列

2016-07-10 18:57 405 查看
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

const int maxn=1000;
char post[maxn],in[maxn];

struct Node {
char val;
Node *left,*right;
Node(char v=0,Node *l=NULL,Node *r=NULL):val(v),left(l),right(r){}
};

Node *makeTree(int i,int j,int size) //i表示后序遍历序列的开始下标,j是中序遍历的下标,size表示序列长度
{
if(size==0) //size为空说明子树为空树,返回NULL
return NULL;
int root;
for(int k=j;k<j+size;k++) //选择后序遍历中的根在中序遍历序列中的位置,由此确定左右子树的节点个数,root一定可以找到
{
if(post[i+size-1]==in[k])
{
root=k;break;
}
}
int leftNum=root-j; //左子树的节点个数
int rightNum=size-leftNum-1;//右子树的节点个数
Node *left=makeTree(i,j,leftNum);//i+1为左子树的根
Node *right=makeTree(i+leftNum,root+1,rightNum);//i+leftNum+1为右子树的根
Node *r=new Node(post[i+size-1],left,right);//生成根节点
return r;
}
void deleteTree(Node *root)//递归删除树
{
if(root==NULL) return;
deleteTree(root->left);
deleteTree(root->right);
delete root;
}

void preOrder(Node *root)
{
if(!root) return;
printf("%c",root->val);
preOrder(root->left);
preOrder(root->right);
}

int main()
{
#ifdef LOCAL_DEBUG
freopen("input.txt","r",stdin);
#endif

while(~scanf("%s%s",post,in))
{
Node *root = makeTree(0,0,strlen(post));
preOrder(root);
deleteTree(root);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: