8 ms simple c++ solution


  • 0
    P
    class Solution {
    public:
        vector<int> rightSideView(TreeNode *root) {
            vector<int> res;
            if (!root) return res;
            queue<TreeNode*> q;
            queue<TreeNode*> aux;
            q.push(root);
            while(!q.empty()) {
                TreeNode* n = q.front();
                q.pop();
                if (q.empty()) res.push_back(n->val);
                if (n->left) aux.push(n->left);
                if (n->right) aux.push(n->right);
                if  (q.empty()) {
                    while(!aux.empty()) {
                        q.push(aux.front());
                        aux.pop();
                    }
                }
            }
            return res;
        }
    };

  • 0
    H
    class Solution {
    public:
    	vector<int> rightSideView(TreeNode *root) {
            vector<int> res;
            helper(root, res, 0);
    		return res;
    	}
        
        void helper(TreeNode *root, vector<int> &res, int level) {
            if (root == NULL) return;
            if (res.size() <= level) 
                res.push_back(root->val);
            helper(root->right, res, level + 1);
            helper(root->left, res, level + 1);
        }
    };

Log in to reply
 

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