30 Day Challenge Day 18 | Leetcode199. Binary Tree Right Side View

题解

Medium

Tree + BFS

class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        if(!root) return {};
        
        vector<int> ret;
        
        queue<TreeNode*> q;
        q.push(root);
        
        while(!q.empty()) {
            int sz = q.size();
            for(int i = 0; i < sz; i++) {
                auto t = q.front();
                q.pop();
                if(i == sz-1) ret.push_back(t->val);
                if(t->left) q.push(t->left);
                if(t->right) q.push(t->right);
            }
        }
        
        return ret;
    }
};
原文地址:https://www.cnblogs.com/casperwin/p/13763381.html