share my C++ solution


  • 0
    N
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        static void dfs(TreeNode* c, string s, vector<string>& ans){
            if (c == NULL) return;
            string t = "";
            s = (s == ""? s + to_string(c->val) : s + "->" + to_string(c->val));
            if (c->left == NULL && c->right == NULL){
                ans.push_back(s);
                return;
            }
            dfs(c->left, s, ans);
            dfs(c->right, s, ans);
        }
    
        vector<string> binaryTreePaths(TreeNode* root) {
            vector<string> ret;
            string s = "";
            dfs(root, s, ret);
            return ret;
        }
    };
    

Log in to reply
 

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