Share my 4ms C++ solution with recursion


  • 0
    X
    class Solution 
    {
    private:
        void dfs(TreeNode* root, vector<int>& path)
        {
            if(root == NULL)    return;
            path.push_back(root->val);
            if(root->left == NULL && root->right == NULL)   return;
            vector<int> rightP, leftP;
            dfs(root->right, rightP);
            dfs(root->left, leftP);
            path.insert(path.end(), rightP.begin(), rightP.end());
            if(leftP.size() > rightP.size())
                path.insert(path.end(), leftP.begin() + rightP.size(), leftP.end());
        }
    public:
        vector<int> rightSideView(TreeNode* root) 
        {
            vector<int> res;
            if(root == NULL)    return res;
            dfs(root, res);
            return res;
        }
    };

Log in to reply
 

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