My C++ solution 8ms


  • 0
    S

    My C++ solution

    class Solution {
    public:
        vector<int> rightSideView(TreeNode *root) {
            int res_cur,count_cur;
    		int iter,count,start;
    		vector<TreeNode*> stack;
    		vector<int> res;
    		
    		if(!root)
    			return res;
    		stack.push_back(root);
    		res.push_back(root->val);	
    		for(start=0,count=1;count;){
    			count_cur=0;
    			for(iter=start;iter<start+count;iter++){
    				if(stack[iter]->left){
    					count_cur++;
    					res_cur=stack[iter]->left->val;
    					stack.push_back(stack[iter]->left);
    				}
    				if(stack[iter]->right){
    					count_cur++;
    					res_cur=stack[iter]->right->val;
    					stack.push_back(stack[iter]->right);
    				}
    			}
    			start+=count;
    			count=count_cur;
    			if(count)
    				res.push_back(res_cur);
    		}
    		return res; 
        }
    };

  • 0
    S

    Level Traversal and visit the node on right side of each level


  • 0
    S
    // Level Traversal    
    class Solution {
        public:
            vector<int> rightSideView(TreeNode* root) {
                vector<int> v;
        		TreeNode* node = root;
        		queue<TreeNode *> nq;
        		int lc = 0, vc = 1;
        		while (node) {
        			if (--vc == 0) { // at the right side node
        				v.push_back(node->val);
        			}
        			if (node->left) {
        				nq.push(node->left);
        				++lc; // increase the node count of current level
        			}
        			if (node->right) {
        				nq.push(node->right);
        				++lc; // increase the node count of current level
        			}
        			if (vc == 0) { // next level
        				vc = lc; lc = 0;
        			}
        			if (nq.empty()) break;
        			node = nq.front();
        			nq.pop();
        		}
                return v;
            }
        };

Log in to reply
 

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