class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 求二叉树的右视图
     * @param xianxu int整型vector 先序遍历
     * @param zhongxu int整型vector 中序遍历
     * @return int整型vector
     */
    vector<int> solve(vector<int>& xianxu, vector<int>& zhongxu) {
        // write code here
        TreeNode* cur;
        vector<vector<int>> res;
        cur=reConstructBinaryTree(xianxu, zhongxu);
        res=levelOrder(cur);
        vector<int> tmp;
        for(int i=0;i<res.size();i++){
            tmp.push_back(res[i][res[i].size()-1]);
        }
        return tmp;
    }
    
     vector<vector<int> > levelOrder(TreeNode* root) {
        // write code here
        vector< vector<int> > res;
        if(root==NULL){
            return res;
        }
        queue<TreeNode*> q;
        q.push(root);
        TreeNode* cur;
        //BFS 广度优先搜索
        while(!q.empty()){
            vector<int> row;
            int len=q.size();
            for(int i=0;i<len;i++){
                cur=q.front();
                q.pop();
                row.push_back(cur->val);
                if(cur->left)
                    q.push(cur->left);
                if(cur->right)
                    q.push(cur->right);
            }
            res.push_back(row);
        }
        return res;
    }
    
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
        int len1=pre.size();
        int len2=vin.size();
        if(len2==0 || len1==0){
            return NULL;
        }
        TreeNode* root= new TreeNode(pre[0]);
        for(int i=0;i<len2;i++){
            //找到中序遍历第一个元素
            if(pre[0]==vin[i]){
                //左子树前序遍历
                vector<int> leftpre(pre.begin()+1,pre.begin()+i+1);
                //左子树中序遍历
                vector<int> leftvin(vin.begin(),vin.begin()+i);
                //左子树构建
                root->left=reConstructBinaryTree(leftpre, leftvin);
                //右子树前序遍历
                vector<int> rightpre(pre.begin()+i+1,pre.end());
                //右子树中序遍历
                vector<int> rightvin(vin.begin()+i+1,vin.end());
                //右子树构建
                root->right=reConstructBinaryTree(rightpre, rightvin);
                break;
            }
        }
        return root;
    }
};