C++ easy solution using queue (with comments)


  • 0
    S
    class Solution {
    public:
        vector<int> rightSideView(TreeNode* root) 
        {
            queue<TreeNode*> que;
            vector<int> vec;
            if(root)que.push(root);
            while(!que.empty())
            {
                int size = que.size();
                while (size>1) // remove all but last element at a level and add their children to que
                {
                    root=que.front();
                    if(root->left) que.push(root->left) ;
                    if(root->right)que.push(root->right);
                    que.pop();
                    size--;
                }
                root=que.front();  //  last node at a level
                vec.push_back(root->val); // get value of last node 
                if(root->left) que.push(root->left) ;    // add children of last node
                if(root->right)que.push(root->right);
                    que.pop();
                
            }
            return vec;
            
        }
    };

Log in to reply
 

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