My C++ DFS solution 6ms


  • 0
    E
    class Solution {
    public:
        vector<string> binaryTreePaths(TreeNode* root) {
            vector<string> res;
            if(!root) return res;
            string s;
            dfs(root, res, s);
            return res;
        }
        
        void dfs(TreeNode* node, vector<string>& res, string s) {
            if(node) {
                s = s + to_string(node->val);
                auto temp = s;
                if(node->left == nullptr && node->right == nullptr) res.push_back(s);
                if(node->left) { s = temp + "->"; dfs(node->left, res, s); }
                if(node->right) { s = temp + "->"; dfs(node->right, res, s); }
            } 
        }
    };
    

Log in to reply
 

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