9 lines concise and easy understand c++ solution


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

Log in to reply
 

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