Javascript solution using recursion


  • 0
    S
    /**
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {TreeNode} root
     * @return {string[]}
     */
    var binaryTreePaths = function(root) {
        var res = [];
        helper(root, '', res);
        
        return res;
    };
    
    var helper = function(root, path, res) {
        if (!root) { return; }
        if (root.left === null && root.right === null) {
            path = `${path}${root.val}`;
            res.push(path);
            return;
        }
        
        path = `${path}${root.val}->`;
        if (root) { helper(root.left, path, res); }
        if (root) { helper(root.right, path, res); }
    };
    

Log in to reply
 

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