题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1710
题目描述:知道二叉树先序遍历序列和中序遍历序列,输出后序遍历序列.
解题思路:先序遍历序列的第一个值为根节点,在中序遍历序列中找到根节点所在位置.中序遍历序列根节点之前的序列为左孩子树的所有节点,之后的序列为右孩子树的所有节点.接着又在先序遍历序列中找到左右子树根节点,照次递归建立二叉树.
- #include <iostream>
- #include <vector>
- #include <string>
- using namespace std;
- struct BiNode
- {
- string data;
- BiNode *lChild;
- BiNode *rChild;
- };
- typedef BiNode* BiTree;
- //建立树
- void CreatBinaryTree(BiTree &T,vector<string>::const_iterator preIter,vector<string>::const_iterator inIter,int len)
- {
- if(len<=0)
- {
- T=NULL;
- return;
- }
- T=new BiNode;
- T->data=*preIter;
- vector<string>::const_iterator inIterOrigin=inIter;
- for(int i=0;i<len;++i)
- {
- if(*inIter==*preIter)
- break;
- inIter++;
- }
- CreatBinaryTree(T->lChild,preIter+1,inIterOrigin,i);
- CreatBinaryTree(T->rChild,preIter+1+i,inIterOrigin+i+1,len-1-i);
- }
- void DestroyBinaryTree(BiTree &T)//删除树
- {
- if(T==NULL)
- return;
- DestroyBinaryTree(T->lChild);
- DestroyBinaryTree(T->rChild);
- delete T;
- }
- void PrintPostOrderTree(const BiTree &T,const string &rootValue)//后序遍历输出节点值
- {
- if(T==NULL)
- return;
- PrintPostOrderTree(T->lChild,rootValue);
- PrintPostOrderTree(T->rChild,rootValue);
- cout<<T->data;
- if(T->data != rootValue)
- cout<<" ";
- }
- int main()
- {
- int i,len;
- string temp,rootValue;
- vector<string> preOrder,inOrder;
- BiTree T;
- while(cin>>len)
- {
- preOrder.clear();
- inOrder.clear();
- for(i=0;i<len;++i)
- {
- cin>>temp;
- preOrder.push_back(temp);
- }
- for(i=0;i<len;++i)
- {
- cin>>temp;
- inOrder.push_back(temp);
- }
- rootValue=preOrder[0];//根节点值
- CreatBinaryTree(T,preOrder.begin(),inOrder.begin(),len);
- PrintPostOrderTree(T,rootValue);
- cout<<endl;
- DestroyBinaryTree(T);
- }
- return 0;
- }