生成二叉树的题目还是有点思考量的,所以在这里存个档
1. 前序遍历+中序遍历。生成二叉树
leetcode版本1
/**
* 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> pos;
vector<int> preorder, inorder;
TreeNode* buildTree(vector<int>& preorder_, vector<int>& inorder_) {
preorder = preorder_;
inorder = inorder_;
int n = inorder_.size();
for (int i = 0; i < n; i ++ ) pos[inorder_[i]] = i;
return build(0, n - 1, 0, n - 1);
}
TreeNode* build(int il, int ir, int pl, int pr) {
TreeNode* root = new TreeNode(preorder[pl]);
int k = pos[root->val];
// x - (pl + 1) = k - 1 - il;
if (il < k) root->left = build(il, k - 1, pl + 1, pl + 1 + k - 1 - il);
if (k < ir) root->right = build(k + 1, ir, pl + 1 + k - 1 - il + 1, pr);
return root;
}
};
leetcode 版本2, 这种方法好像更快
/**
* 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> pos;
vector<int> preorder, inorder;
TreeNode* buildTree(vector<int>& preorder_, vector<int>& inorder_) {
preorder = preorder_;
inorder = inorder_;
int n = inorder_.size();
for (int i = 0; i < n; i ++ ) pos[inorder_[i]] = i;
return build(0, n - 1, 0, n - 1);
}
TreeNode* build(int il, int ir, int pl, int pr) {
if (pl > pr) return nullptr;
TreeNode* root = new TreeNode(preorder[pl]);
int k = pos[root->val];
// x - (pl + 1) = k - 1 - il;
root->left = build(il, k - 1, pl + 1, pl + 1 + k - 1 - il);
root->right = build(k + 1, ir, pl + 1 + k - 1 - il + 1, pr);
return root;
}
};
acwing 版本
2. 后序遍历+中序遍历。生成二叉树
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:
unordered_map<int, int> pos;
vector<int> inorder, postorder;
TreeNode* buildTree(vector<int>& inorder_, vector<int>& postorder_) {
inorder = inorder_;
postorder = postorder_;
for (int i = 0; i < inorder.size(); i ++ ) pos[inorder[i]] = i;
return build(0, inorder.size() - 1, 0, inorder.size() - 1);
}
TreeNode* build(int il, int ir, int pl, int pr) {
if (pl > pr) return nullptr;
TreeNode* root = new TreeNode(postorder[pr]);
int k = pos[root->val];
// x - pl = k - 1 - il
root->left = build(il, k - 1, pl, pl + k - 1 - il);
root->right = build(k + 1, ir, pl + k - 1 - il + 1, pr - 1);
return root;
}
};
acwing 版本