Simple iterative solution


  • 0
    H
    vector<int> rightSideView(TreeNode* root) {
            if(root == NULL) return vector<int>();
            
            vector<int> ret;
            queue<pair<int, TreeNode*>> q;
            q.push(make_pair(0, root));
        
            int level = 0;
            while(!q.empty()) {
                
                TreeNode * next = q.front().second;
                int l = q.front().first;
                
                if (l == level) {
                    ret.push_back(next->val);
                    level++;
                }
                q.pop();
                if (next->right) q.push(make_pair(l+1, next->right));
                if (next->left) q.push(make_pair(l+1, next->left));
            }
            
            return ret;
            
        }
    

Log in to reply
 

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