classSolution{public:TreeNode*buildTree(vector<int>& preorder, vector<int>& inorder){if(preorder.size()==0){returnnullptr;}int val = preorder[0];int index =0;for(int i =0; i < inorder.size(); i++){if(inorder[i]== val){index = i;}}vector<int> left_preorder;vector<int> right_preorder;vector<int> left_inorder;vector<int> right_inorder;for(int i =0; i < index; i++){left_inorder.push_back(inorder[i]);}for(int i = index +1; i < inorder.size(); i++){right_inorder.push_back(inorder[i]);}for(int i =1; i <= index; i++){left_preorder.push_back(preorder[i]);}for(int i = index +1; i < preorder.size(); i++){right_preorder.push_back(preorder[i]);}TreeNode* node =newTreeNode(val);node->left =buildTree(left_preorder, left_inorder);node->right =buildTree(right_preorder, right_inorder);return node;}};
classSolution{public:TreeNode*buildTree(vector<int>& inorder, vector<int>& postorder){if(postorder.size()==0){returnnullptr;}int val = postorder[postorder.size()-1];int index =0;for(int i =0; i < inorder.size(); i++){if(inorder[i]== val){index = i;}}TreeNode* node =newTreeNode(val);vector<int> left_inorder;vector<int> right_inorder;vector<int> left_postorder;vector<int> right_postorder;for(int i =0; i < index; i++){left_inorder.push_back(inorder[i]);}for(int i = index +1; i < inorder.size(); i++){right_inorder.push_back(inorder[i]);}for(int i =0; i < index; i++){left_postorder.push_back(postorder[i]);}for(int i = index; i < postorder.size()-1; i++){right_postorder.push_back(postorder[i]);}node->left =buildTree(left_inorder, left_postorder);node->right =buildTree(right_inorder, right_postorder);return node;}};