Simple DFS solution


  • -1
    J

    class Solution {
    public:
    vector<string> binaryTreePaths(TreeNode* root) {
    vector<string> res;
    if (root == NULL)
    return res;

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

    };


Log in to reply
 

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