Recursive JavaScript solution


  • 1
    L
    function binaryTreePaths(root) {
        var res = [];
        var prefix = [];
        
        traverse(root);
        return res;
        
        function traverse(n) {
            if (!n) {
                return;
            }
            
            prefix.push(n.val);
            
            if (!n.left && !n.right) {
                res.push(prefix.join('->'));
            } else {
                traverse(n.left);
                traverse(n.right);
            }
            
            prefix.pop();
        }
    }

Log in to reply
 

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