Clean 4ms recursive solution


  • 0
    W

    Simple recursive solution:

    class Solution {
    public:
        void preorder(TreeNode* root, string cur, vector<string> &res){
            cur += to_string(root->val);
            if (root->left == NULL && root->right == NULL){
                res.push_back(cur);
                return;
            }  else {
                cur += "->";
            }
            if (root->left) preorder(root->left, cur, res);
            if (root->right) preorder(root->right, cur, res);
            
        }
        vector<string> binaryTreePaths(TreeNode* root) {
            vector<string> res;
            if (root)  preorder(root, "", res);
            return res;
        }
    };

Log in to reply
 

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