您的位置:首页 > 其它

重建二叉树

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},则重建二叉树并输出它的后序遍历序列。(测试用例中,"树"的输出形式类似于树的层次遍历,没有节点的用#来代替)

解答思路:二叉树的操作,一定要记得使用递归的思路

/**
* 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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: