C++ recursive solution


  • 0
    T

    Here is the solution of the exercice by recursive. We build the branch by using tail recursive.

    class Solution {
        vector<string> result;
    public:
        void dfs(TreeNode* root, string branch){
            if (!root->left && !root->right){
                result.push_back(branch);
                return;
            }
            if (root->left) dfs(root->left,branch + "->" + to_string(root->left->val));
            if (root->right) dfs(root->right,branch + "->" + to_string(root->right->val));
            return;
        }
        vector<string> binaryTreePaths(TreeNode* root) {
            if (!root) return result;
            dfs(root, to_string(root->val));
            return result;
        }
    };
    

Log in to reply
 

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