C++ 8ms recursive


  • 2
    C

    What I figured is recursive solutions are as good as custom stack based methods. It will be clearer in the code as well.

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

  • 0
    S

    That‘s a good solution


Log in to reply
 

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