
- class Solution {
- public:
- vector<int> rightSideView(TreeNode* root) {
- unordered_map<int,int> rightmostvalue;
- queue
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;
- }
- };
- class Solution {
- public:
- vector<int> rightSideView(TreeNode* root) {
- vector<int> res = {};
- if(root == nullptr) return res;
- queue
que; - TreeNode* cur = root;
- que.push(cur);
- int size = 0;
- while (!que.empty()) {
- size = que.size();
- while (size--){
- TreeNode* node = que.front();
- if (size == 0) {
- res.emplace_back(node->val);
- }
- que.pop();
- if (node->left) que.push(node->left);
- if (node->right) que.push(node->right);
- }
- }
- return res;
- }
- };
- class Solution {
- public:
- vector<int> rightSideView(TreeNode* root) {
- vector<int> res;
- if (!root) return res;
- queue
q; - TreeNode* cur = root;
- q.push(cur);
- while (!q.empty()) {
- int size = q.size();
- while (size--) {
- TreeNode* node = q.front();
- if (size == 0) res.emplace_back(node->val);
- q.pop();
- if (node->left) q.push(node->left);
- if (node->right) q.push(node->right);
- }
- }
- return res;
- }
- };