已知数的前序和中序遍历,求后序遍历和层序遍历的序列
树的存储结构定为链式存储结构,首先需要建树buildTree(),然后用递归遍历PostTraverse()产生后序遍历,借用队列实现层序遍历:
实现代码:
#include <iostream> #include <string> #include <queue> using namespace std; struct TreeNode{ char val; TreeNode *left,*right; }; TreeNode * bulidTree(string pre,string in){ TreeNode * root =NULL; if (pre.length() > 0) { root = new TreeNode; root->val = pre[0]; int index = in.find(pre[0]); root->left = bulidTree(pre.substr(1,index),in.substr(0,index)); root->right = bulidTree(pre.substr(index+1),in.substr(index+1)); } return root; } void PostTraverse(TreeNode * root){ if (root != NULL) { PostTraverse(root->left); PostTraverse(root->right); cout<<root->val; } } void FTraverse(TreeNode * root) { queue<TreeNode> Q; Q.push(*root); while(!Q.empty()) { TreeNode tmp = Q.front(); if(tmp.left!=NULL) Q.push(*tmp.left); if(tmp.right!=NULL) Q.push(*tmp.right); cout << tmp.val; Q.pop(); } } int main(){ string prestr,instr; while(cin>>prestr>>instr){ TreeNode * root =bulidTree(prestr,instr); PostTraverse(root); cout<<" "; FTraverse(root); cout<<endl; } return 0; }