/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
unordered_map<int, int> idx;
TreeNode* buildingTree(vector<int> preorder, vector<int> inorder, int preleft, int preright, int inleft, int inright) {
if(preleft > preright) {
return nullptr;
}
// 先序对应根结点下标
int preroot = preleft;
// 中序对应根结点下标
int inroot_idx = idx[preorder[preleft]];
TreeNode* root = new TreeNode(preorder[preleft]);
int leftTreeSize = inroot_idx - inleft;
root->left = buildingTree(preorder, inorder, preleft + 1, preleft + leftTreeSize, inleft, inroot_idx - 1);
root->right = buildingTree(preorder, inorder, preleft + leftTreeSize + 1, preright, inroot_idx + 1, inright);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int n = inorder.size();
for(int i = 0; i < n; i++) {
idx[inorder[i]] = i;
}
return buildingTree(preorder, inorder, 0, n - 1, 0, n - 1);
}
};
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!