您的位置:首页 > Web前端

《剑指Offer》学习笔记——重建二叉树

2016-04-05 20:16 344 查看
题目描述:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。

假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

#include <vector>
#include <string>
#include <algorithm>
using namespace std;

struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x):val(x),left(nullptr),right(nullptr){}
};

class Solution{
public:
struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) {
int size = pre.size();
if(size == 0){
return nullptr;
}
return PreInBuildTree(pre,in,0,0,size);
}
private:
TreeNode* PreInBuildTree(vector<int> preorder,vector<int> inorder,int preIndex,int inIndex,int size){
if(size == 0){
return nullptr;
}
// 根节点
TreeNode* root = new TreeNode(preorder[preIndex]);
// 寻找根节点在中序遍历数组的下标
int index = 0;
for(int i = 0;i < size;++i){
// 注意:inorder[inIndex+i]
if(preorder[preIndex] == inorder[inIndex+i]){
index = inIndex+i;
break;
}
}
// 左子树个数
int leftSize = index - inIndex;
// 右子树个数
int rightSize = size - leftSize - 1;
// 左子树
root->left = PreInBuildTree(preorder,inorder,preIndex+1,inIndex,leftSize);
// 右子树
root->right = PreInBuildTree(preorder,inorder,preIndex+1+leftSize,index+1,rightSize);
return root;
}
};




参考:http://blog.csdn.net/sunnyyoona/article/details/46966143
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: