105. 从前序与中序遍历序列构造二叉树 - 力扣(LeetCode)
/*** 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:int n;unordered_map<int, int> pos;TreeNode* build(vector<int> &preorder, vector<int> &inorder, int il, int ir, int pl, int pr){TreeNode* root = new TreeNode(preorder[pl]);int k = pos[root->val];if (il < k) //如果左子树存在,递归构建左子树root->left = build(preorder, inorder, il, k - 1, pl + 1, pl + 1 + k - 1 - il);if (ir > k) //如果右子树存在,递归构建右子树root->right = build(preorder, inorder, k + 1, ir, pl + 1 + k - 1 - il + 1, pr);return root;}TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {n = preorder.size();for (int i = 0; i < n; i++) pos[inorder[i]] = i;return build(preorder, inorder, 0, n - 1, 0, n - 1);}
};
106. 从中序与后序遍历序列构造二叉树 - 力扣(LeetCode)
/*** 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:int n;unordered_map<int, int> pos;TreeNode* build(vector<int> &inorder, vector<int> &postorder, int il, int ir, int pl, int pr){TreeNode* root = new TreeNode(postorder[pr]);int k = pos[root->val];if (il < k) root->left = build(inorder, postorder, il, k - 1, pl, pl + k - 1 - il);if (ir > k) root->right = build(inorder, postorder, k + 1, ir, pl + k - 1 - il + 1, pr - 1);return root;}TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {n = inorder.size();for (int i = 0; i < n; i++) pos[inorder[i]] = i;return build(inorder, postorder, 0, n - 1, 0, n - 1);}
};