One queue, O(n) 10ms simple c++ solution


  • 0
    C
    struct QueueElement {
    
    	TreeNode* node_ ;
    	int			  level_;
    
    	QueueElement(TreeNode* node, int level) : node_(node), level_(level) {}
    };
    
    class Solution {
    public:
        vector<int> rightSideView(TreeNode *root) {
        			
    			queue<QueueElement> my_queue;
    			my_queue.push(QueueElement(root, 0));
    
    			map<int, int> map_result;
    			while (!my_queue.empty()) {				
    
    				QueueElement &elt = my_queue.front();
    
    				if (elt.node_ == NULL) {
    
    					my_queue.pop();
    					continue;
    				}
    
    				int level         = elt.level_    ;
    				map_result[level] = elt.node_->val;
    
    				my_queue.push(QueueElement(elt.node_->left , level + 1));
    				my_queue.push(QueueElement(elt.node_->right, level + 1));
    
    				my_queue.pop();
    			}
    
    			vector<int> result;						
    			for (pair<int, int> a_pair : map_result)
    				result.push_back(a_pair.second);
    
    			return result;
        }
    };

Log in to reply
 

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