class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 求二叉树的右视图 * @param preOrder int整型vector 先序遍历 * @param inOrder int整型vector 中序遍历 * @return int整型vector */ unordered_map<int,int> hash; TreeNode*answer1(int left1,int right1,int left2,int right2,vector <int> preOrder,vector <int> inOrder) { if(left1<=right1 && left2<=right2) { TreeNode*ans=new TreeNode(preOrder[left1]); int m=hash[preOrder[left1]]; int n=m-left2; ans->left=answer1(left1+1,left1+n,left2,m-1,preOrder,inOrder); ans->right=answer1(left1+n+1,right1,m+1,right2,preOrder,inOrder); return ans; } return NULL; } int height(TreeNode*root) { if(root) { int m=height(root->left); int n=height(root->right); return max(m,n)+1; } return 0; } void answer3(TreeNode*root,int h,vector <vector <int>>&ans) { if(root) { answer3(root->left,h+1,ans); ans[h].push_back(root->val); answer3(root->right,h+1,ans); } } vector<int> solve(vector<int>& preOrder, vector<int>& inOrder) { int i=0; int len=preOrder.size(); for(i=0;i<len;i++) { hash[inOrder[i]]=i; } TreeNode* ans2=answer1(0,len-1,0,len-1,preOrder,inOrder); int h=height(ans2); vector <vector <int>>ans(h); answer3(ans2,0,ans); vector <int> z; for(i=0;i<h;i++) { int len3=ans[i].size(); z.push_back(ans[i][len3-1]); } return z; } };