My simple c++ solution, easy to understand.


  • 0
    T
    class Solution {
    public:
        vector<string> binaryTreePaths(TreeNode* root) {
            vector<string> ret;
            if (!root) return ret;
            if (!root->left && !root->right) return {to_string(root->val)};
            auto lv = binaryTreePaths(root->left);
            auto rv = binaryTreePaths(root->right);
            for (auto &s : lv) ret.push_back(to_string(root->val)+"->" + s);
            for (auto &s : rv) ret.push_back(to_string(root->val)+"->" + s);
            return ret;
        }
    };
    

    key to think about binaryTreePaths return the current root all paths, so we just add the root->val to the return path.


Log in to reply
 

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