POJ 2255 根据二叉树的前序和中序序列来重建二叉树
2010-11-16 18:05
591 查看
根据二叉树的前序和中序序列来重建二叉树,输出其后序序列
这是面试笔试中经常遇到的问题
关键要理解在前序和中序序列中找左右子树的前序和中序序列的方法,利用递归实现
另外字符串的标准库函数要活用
这是面试笔试中经常遇到的问题
关键要理解在前序和中序序列中找左右子树的前序和中序序列的方法,利用递归实现
另外字符串的标准库函数要活用
#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; }
相关文章推荐
- 根据二叉树的前序和中序序列来重建二叉树
- poj2255 根据二叉树的前序和中序遍历 求出树的后序遍历
- 根据中序和后序序列重建二叉树 Construct Binary Tree from Inorder and Postorder Traversal
- 【面试题】剑指Offer-6-根据前序和中序遍历重建二叉树
- 根据前序遍历序列和中序遍历序列重建二叉树
- 根据给定先序和中序序列来重建二叉树
- POJ 2255Tree Recovery 二叉树重建(根据前序遍历和中序遍历写出后序遍历)
- 根据前序和中序序列重建二叉树 Construct Binary Tree from Preorder and Inorder Traversal
- [面试] 根据前序和中序重建二叉树,并且中序非递归遍历
- 根据前序和中序的遍历序列重建二叉树
- 【构建二叉树】01根据前序和中序序列构造二叉树【Construct Binary Tree from Preorder and Inorder Traversal】
- poj2255 根据任意二叉树的先序遍历和中序遍历求解后序遍历
- [LeetCode] 根据中序和后序序列重建二叉树
- [面试] 根据前序和中序重建二叉树,并且中序非递归遍历
- 根据二叉树 前序和中序 重建原二叉树
- 剑指offer刷题之c++实现的根据二叉树的前序和中序遍历重建二叉树
- 根据前序和中序遍历序列重构二叉树 代码完整版
- 根据前序和中序列 重建二叉树
- 根据先序遍历序列和中序遍历序列重建二叉树
- 根据中序和先序重建二叉树+二叉树的镜像+二叉树的深度+判断后序序列+判断子树