文章目录
题目
解法分析
根据解题分析的规律递归分治
我们用前序遍历的数组序列不断的进行递归分治
既然是递归分治,所以我们需要确定每一个分治情况下的范围,所以正好可以根据中序遍历得到范围。
class Solution {
public:
unordered_map<int,int>table;
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if(!preorder.size())
return nullptr;
//构建table
for(int i=0;i<inorder.size();i++){
table[inorder[i]] = i;
}
return buildTree(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
}
private:
TreeNode* buildTree(vector<int>&preorder,int preLeft,int preRight,
vector<int>&inorder, int inLeft,int inRight){
if(preLeft>preRight||inLeft>inRight)
return nullptr;
//获取当前根节点
TreeNode* root = new TreeNode(preorder[preLeft]);
//根据该根节点在中序遍历数组中的下标位置更新左右子树的范围
int pIndex = table[preorder[preLeft]];
root->left = buildTree(preorder,preLeft+1,preLeft-inLeft+pIndex,
inorder,inLeft,pIndex-1);
root->right = buildTree(preorder,preLeft-inLeft+pIndex+1,preRight,
inorder,pIndex+1,inRight);
return root;
}
};