题目:
代码(首刷看解析):
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
unordered_map<int,int> rightmostvalue;
queue<TreeNode*> nodeQueue;
queue<int> depthQueue;
int maxDepth=-1;
nodeQueue.push(root);
depthQueue.push(0);
while(!nodeQueue.empty()){
TreeNode* node = nodeQueue.front();nodeQueue.pop();
int depth = depthQueue.front();depthQueue.pop();
if(node!=nullptr){
maxDepth = max(maxDepth,depth);
//下面这一行运用了unordered_map的特性更新,直到最右值
rightmostvalue[depth]=node->val;
nodeQueue.push(node->left);
nodeQueue.push(node->right);
depthQueue.push(depth+1);
depthQueue.push(depth+1);
}
}
vector<int> ans;
for(int i=0;i<=maxDepth;++i){
ans.push_back(rightmostvalue[i]);
}
return ans;
}
};