题目:

代码(首刷看解析 2024年1月30日):
class Solution {
public:TreeNode* recursion(vector<int>& inorder, vector<int>& postorder, int longthOfLeft, int longthOfRight) {if (postorder.size() == 0) return nullptr;int splitPoint = postorder[postorder.size() - 1];TreeNode* root = new TreeNode(splitPoint);if (postorder.size() == 1) return root;int arrayLeft = 0;for (int i = 0; i < inorder.size(); ++i) {if (inorder[i] == splitPoint) {arrayLeft = i;break;}}int arrayRight = inorder.size() - arrayLeft - 1;vector<int> inorderLeft(inorder.begin(), inorder.begin() + arrayLeft);vector<int> inorderRight(inorder.begin() + arrayLeft + 1, inorder.end());postorder.resize(postorder.size() - 1);vector<int> postorderLeft(postorder.begin(), postorder.begin() + arrayLeft);vector<int> postorderRight(postorder.begin() + arrayLeft, postorder.end());root->left = recursion(inorderLeft,postorderLeft,arrayLeft,arrayRight);root->right = recursion(inorderRight,postorderRight,arrayLeft,arrayRight);return root;}TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {int splitPoint = postorder[postorder.size() - 1];int arrayLeft = 0;for (int i = 0; i < inorder.size(); ++i) {if (inorder[i] == splitPoint) {arrayLeft = i;break;}}int arrayRight = inorder.size() - arrayLeft - 1;return recursion(inorder,postorder,arrayLeft,arrayRight);}
};
思路
