level order c++ solution


  • 0
    D

    always select the rightmost node in every tree level, the space is O(n), the time complexity is also O(n) .

    class Solution {
    public:
        vector<int> rightSideView(TreeNode* root) {
            if(!root) return {};
            vector<int> views;
            queue<TreeNode*> q;
            q.push(root);
            int level_size = 0;
            while(!q.empty()) {
                level_size = q.size();
                views.push_back(q.back() -> val);
                while(level_size--) {
                    TreeNode* node = q.front();
                    q.pop();
                    if(node -> left) q.push(node -> left);
                    if(node -> right) q.push(node -> right);
                }
            }
            return views;
        }
    };
    

Log in to reply
 

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