这一题是根据先序序列和中序序列建立二叉树,然后求后序序列。首先是输入问题,我采用stringstream来输入,然后递归建立二叉树,最后后序遍历二叉树,具体代码如下:
#include <iostream>
#include <sstream>
#include <string>
#include <cstdio>
using namespace std;
struct Node
{
char value;
Node* left;
Node* right;
Node():left(NULL),right(NULL){}
};
string preorder; //先序序列
string inorder; //中序序列
//preorder[L1,R1],inorder[L2,R2]
Node* buildTree(int L1,int R1,int L2,int R2)
{
if(L2>R2) //当中序序列的L2>R2时终止递归
return NULL;
Node* root=new Node();
root->value=preorder[L1];
int pos=0;
for(;pos<inorder.length();pos++)
if(inorder[pos]==preorder[L1])
break;
int cnt=pos-L2; //左子树结点个数
root->left=buildTree(L1+1,L1+cnt,L2,pos-1);
root->right=buildTree(L1+cnt+1,R1,pos+1,R2);
return root;
}
void postOrder(Node* root) //后序遍历二叉树
{
if(root==NULL)
return;
postOrder(root->left);
postOrder(root->right);
cout<<root->value;
}
int main()
{
//freopen("test.txt","r",stdin);
string input;
while(getline(cin,input)) //输入
{
stringstream ss(input);
ss>>preorder>>inorder;
int len=preorder.length();
Node* root=buildTree(0,len-1,0,len-1);
postOrder(root);
cout<<endl;
}
return 0;
}
做完这一题后,可以做uva548,这一题是根据后序序列和中序序列建立二叉树,然后再求解,两题在一起做效果最好。我的关于uva548的题解在此。
本文介绍如何根据先序和中序序列构建二叉树,并实现后序遍历。通过递归方法创建二叉树节点,再利用后序遍历输出节点值。适用于UVa 548等类似问题。
627

被折叠的 条评论
为什么被折叠?



