3ms BFS C++ solution, beating 100%


  • 0
    H
    class Solution {
    public:
        vector<int> rightSideView(TreeNode* root) {
            vector<int> res;
            if (!root) return res;
            bfs(root, res);
            return res;
        }
        void bfs(TreeNode* root, vector<int>& res) {
            deque<TreeNode*> queue;
            queue.push_back(root);
            while (!queue.empty()) {
                int size = queue.size();
                res.push_back(queue[size - 1]->val);
                for (int i = 0; i < size; i++) {
                    TreeNode* node = queue.front();
                    queue.pop_front();
                    if (node->left) queue.push_back(node->left);
                    if (node->right) queue.push_back(node->right);
                }
            }
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.