根据二叉树的前序和中序序列来重建二叉树
2012-08-24 12:24
375 查看
根据二叉树的前序和中序序列来重建二叉树,输出其后序序列
这是面试笔试中经常遇到的问题
关键要理解在前序和中序序列中找左右子树的前序和中序序列的方法,利用递归实现
另外字符串的标准库函数要活用
[cpp] view
plaincopy
#include <iostream>
#include <string>
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;
}
}
int main(){
string prestr,instr;
while(cin>>prestr>>instr){
TreeNode * root =bulidTree(prestr,instr);
PostTraverse(root);
cout<<endl;
}
return 0;
}
这是面试笔试中经常遇到的问题
关键要理解在前序和中序序列中找左右子树的前序和中序序列的方法,利用递归实现
另外字符串的标准库函数要活用
[cpp] view
plaincopy
#include <iostream>
#include <string>
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;
}
}
int main(){
string prestr,instr;
while(cin>>prestr>>instr){
TreeNode * root =bulidTree(prestr,instr);
PostTraverse(root);
cout<<endl;
}
return 0;
}
相关文章推荐
- POJ 2255 根据二叉树的前序和中序序列来重建二叉树
- [LeetCode] 根据中序和后序序列重建二叉树
- 根据给定先序和中序序列来重建二叉树
- 剑指offer刷题之c++实现的根据二叉树的前序和中序遍历重建二叉树
- 根据前序遍历序列和中序遍历序列重建二叉树
- 根据前序和中序序列重建二叉树
- 根据前序和中序列 重建二叉树
- 根据前序和中序遍历重建二叉树
- 根据前序和中序遍历序列重构二叉树 代码完整版
- Python练手之根据前序和中序&根据中序和后序重建二叉树,输出前序、中序和后序遍历结果
- 根据中序和后序序列重建二叉树 Construct Binary Tree from Inorder and Postorder Traversal
- 根据前序遍历序列和中序遍历序列重建二叉树
- 根据前序和中序重建二叉树
- 根据先序和中序序列重建二叉树
- 根据前序和中序重建二叉树
- 根据前序和中序序列重建二叉树 Construct Binary Tree from Preorder and Inorder Traversal
- 根据先序遍历序列和中序遍历序列重建二叉树
- 根据前序和中序重建二叉树的代码,出了错误 请指教
- 机试指南-根据二叉树的前序和中序确定后序序列
- 《剑指offer》根据先序序列与中序序列重建二叉树-Java