C++ Non Recursive 6ms solution


  • 0
    S

    Most of the solutions posted here are recursive. I think it is good to have non-recursive solution. This solution is based on (https://discuss.leetcode.com/topic/10469/c-solution-using-only-one-queue-use-a-marker-null)

    class Solution {
        
    public:
    
    
        vector<int> rightSideView(TreeNode* root) {
            vector<int> right_view;
    
            if (!root) return right_view;
            
            queue<TreeNode*> q;
            q.push(root);
            q.push(NULL);
            
            
            int prev;
            
            vector<int> cur_vec;
            
            while(!q.empty()) {
                
                
                TreeNode* t = q.front();
                q.pop();
                if (t==NULL) {
                    right_view.push_back(cur_vec.back());
                    cur_vec.resize(0);
                    if (q.size() > 0) {
                        q.push(NULL);
                    }
               } else {
                    
                    cur_vec.push_back(t->val);
                    if (t->left) q.push(t->left);
                    if (t->right) q.push(t->right);
                  
                    }
                
            }
            return right_view;
    
        }
    };
    

Log in to reply
 

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