c++取vector子串比较麻烦
如果个人感觉两个数组遍历一遍即可出答案,奈何才疏学浅,想不出来,如果大家有更好的方法还请大家分享出来!
/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param inorder int整型vector 中序遍历序列
     * @param postorder int整型vector 后序遍历序列
     * @return TreeNode类
     */
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        // write code here
        if(postorder.size()==0)return nullptr;
        TreeNode* root=new TreeNode(postorder[postorder.size()-1]);
        for(int i=0;i<postorder.size();i++){
            if(root->val==inorder[i]){//截取vector中部分数组 
                vector<int>::const_iterator Fist = inorder.begin(); // 找到第二个迭代器
                vector<int>::const_iterator Second = inorder.begin()+i; // 找到第三个迭代器
                vector<int>::const_iterator Fist2 = postorder.begin(); 
                vector<int>::const_iterator Second2 = postorder.begin()+i; 
                vector<int> inorder2;
                vector<int> postorder2;
                inorder2.assign(Fist,Second);
                postorder2.assign(Fist2,Second2);
                root->left=buildTree(inorder2, postorder2);
                vector<int>::const_iterator Fist3 = inorder.begin()+i+1; 
                vector<int>::const_iterator Second3 = inorder.begin()+inorder.size(); 
                vector<int>::const_iterator Fist4 = postorder.begin()+i; 
                vector<int>::const_iterator Second4 = postorder.begin()+postorder.size()-1;
                vector<int> inorder3;
                vector<int> postorder3;
                inorder3.assign(Fist3,Second3);
                postorder3.assign(Fist4,Second4);
                root->right=buildTree(inorder3,postorder3);
                return root;
            }

        }
        return  root;
    }
};