Very easy to understand Javascript solution using recursion


  • 0
    E
    var binaryTreePaths = function(root) {
        if(!root) return [];
        var traversalNodes = [];
        var lastNode;
    
    //store path from root to current node in TreeNode object
        var visit = function(node, order) {
            if(!lastNode) node.path = node.val.toString();
            else node.path = lastNode.path + ("->" + node.val);
        };
    
        var depthFirstTraverse = function(node) {
            visit(node);
    
            if (node.left) {
                lastNode = node;
                depthFirstTraverse(node.left);
            }
    
            if (node.right) {
                lastNode = node;
                depthFirstTraverse(node.right);
            }
            
            if(!node.left && !node.right) traversalNodes.push(node.path);//push a path when meeting leaves
        };
    
        depthFirstTraverse(root);
        return traversalNodes;
    };
    

Log in to reply
 

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