My solution - #recursive #c++


  • 1
    L
    void DFS(TreeNode* root, string path, vector<string>& res) {
        if(root->left == NULL && root->right==NULL) {
            res.push_back(path);
            return;
        }
        if(root->left)
            DFS(root->left, path+ "->" + to_string(root->left->val), res);            
        if(root->right)
            DFS(root->right, path + "->" + to_string(root->right->val), res);
    }
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res;
        if(root==NULL)
            return res;
        string path = to_string(root->val);
        DFS(root, path, res);
        return res;
    }

Log in to reply
 

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