题解 | #输出二叉树的右视图#
输出二叉树的右视图
http://www.nowcoder.com/practice/c9480213597e45f4807880c763ddd5f0
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 求二叉树的右视图
* @param xianxu int整型vector 先序遍历
* @param zhongxu int整型vector 中序遍历
* @return int整型vector
*/
unordered_map<int, int> index;
//利用哈希表递归建树
TreeNode* buildTree(vector<int>& xianxu,int l1,int r1,vector<int>& zhongxu,int l2,int r2){
if(l1>r1||l2>r2) return nullptr;
int xianxu_root = xianxu[l1];
int zhongxu_root = index[xianxu_root];
TreeNode* root = new TreeNode(xianxu_root);
int leftsize = zhongxu_root-l2;
root->left = buildTree(xianxu, l1+1, l1+leftsize, zhongxu, l2, zhongxu_root-1);
root->right = buildTree(xianxu, l1+leftsize+1, r1, zhongxu, zhongxu_root+1, r2);
return root;
}
//层次遍历找到最右结点
void rightsearch(TreeNode* root,vector<int>& res){
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int s = q.size();
for(int i = 0;i<s;i++){
TreeNode* tmp = q.front();
q.pop();
if(tmp->left!=nullptr) q.push(tmp->left);
if(tmp->right!=nullptr) q.push(tmp->right);
if(i==s-1) res.push_back(tmp->val);
}
}
}
vector<int> solve(vector<int>& xianxu, vector<int>& zhongxu) {
vector<int> res;
if(xianxu.size()==0) return res;
for(int i = 0;i<zhongxu.size();i++){
index[zhongxu[i]] = i;
}
TreeNode* root = buildTree(xianxu, 0, xianxu.size()-1,zhongxu, 0, zhongxu.size()-1);
rightsearch(root,res);
return res;
}
};