C++ 8ms easy solution, a little modification after using bfs to store the elements on the same level


  • 0
    X
    class Solution {
    public:
    vector<int> rightSideView(TreeNode* root) {
        vector<vector<int>> res;
        vector<int> ret;
        if(!root)return ret;
        
        vector<TreeNode*> parent;
        vector<TreeNode*> child;
        parent.push_back(root);
        vector<int> temp_r;
        temp_r.push_back(root->val);
        res.push_back(temp_r);
        while(true)
        {   for(auto it=parent.begin();it!=parent.end();++it)
            {
                if((*it)->left)child.push_back((*it)->left);
                if((*it)->right)child.push_back((*it)->right);
            }
            if(child.size()==0)break;
        
            vector<int> temp;
            for(auto it=child.begin();it!=child.end();it++)
                temp.push_back((*it)->val);
            res.push_back(temp);
            parent=child;
            child.clear();
            temp.clear();
        }
        int len=res.size();
        
        for(int i=0;i<len;i++)
        {
            ret.push_back(res[i].back());
        }
        return ret;
        
        
    }
        
    
    };

Log in to reply
 

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