重建二叉树
2015-06-05 10:54
399 查看
时间限制:1秒空间限制:32768K
通过比例:19.51%
最佳记录:0ms|85(来自 牛客688826号)
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并输出它的后序遍历序列。(测试用例中,"树"的输出形式类似于树的层次遍历,没有节点的用#来代替)
解答思路:二叉树的操作,一定要记得使用递归的思路
通过比例:19.51%
最佳记录:0ms|85(来自 牛客688826号)
题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并输出它的后序遍历序列。(测试用例中,"树"的输出形式类似于树的层次遍历,没有节点的用#来代替)解答思路:二叉树的操作,一定要记得使用递归的思路
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) { if(pre.empty()||in.empty()) return NULL; TreeNode* root=new TreeNode(pre[0]); vector<int> left_child_pre; vector<int> left_child_in; vector<int> right_child_pre; vector<int> right_child_in; int root_sub=0; for(int i=0;i<in.size();++i){ if(in[i]==pre[0]){ root_sub=i; break; } } for(int i=0;i<root_sub;++i){ left_child_pre.push_back(pre[i+1]); left_child_in.push_back(in[i]); } for(int i=root_sub+1;i<pre.size();++i){ right_child_pre.push_back(pre[i]); right_child_in.push_back(in[i]); } root->left=reConstructBinaryTree(left_child_pre,left_child_in); root->right=reConstructBinaryTree(right_child_pre,right_child_in); return root; } };
相关文章推荐
- explicit的作用
- Remove Element -LeetCode
- 如何变相的绕过QQ邮箱订阅的繁琐核审
- linux dmesg命令参数及用法详解(linux显示开机信息命令)
- 反射
- 数据结构和算法-002 数组排序 冒泡排序
- FFmpeg源代码结构图 - 解码
- 项目中采用J2EE体系架构分析
- 基于jQuery+JSON的省市二三级联动效果
- 生产管理流程图
- 二叉树
- 苹果数字签名的一些问题
- 使用开源库zlib压缩和解压文件
- BFC块级化上下文的解决办法
- asp.net目录收放
- [ 原创 ] Linux下查找指定类型文件以及删除
- mysql 常用命令
- 科技圈的监守自盗:富士康内鬼靠盗卖苹果赚外快
- 为什么你会写自嗨型文案?
- [BZOJ3242][Noi2013]快餐店 && 环套树+线段树