Simple C++ solution (BTW: I like clean codes)


  • 30
    S
    class Solution {
    public:
        void dfs(TreeNode* root, int lv, vector<int> &res){
            if(!root)   return;
            if(lv>=res.size()) res.push_back(root->val);
            dfs(root->right,lv+1,res);
            dfs(root->left,lv+1,res);
        }
    
        vector<int> rightSideView(TreeNode* root) {
            vector<int> res;
            dfs(root, 0, res);
            return res;
        }
    };

  • 0
    A

    Nice solution, I think that it's sufficient to test that lv == res.size() before adding to result.


  • 0
    U

    this is really an excellent solution!


Log in to reply
 

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