Binary Tree Paths
Description
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:1 /
2 3
5Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
Solution(javascript)
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {string[]}
*/
const binaryTreePaths = (root) => {
const isLeaf = node => node && (!node.left) && (!node.right)
const join = (current, val) => (current ? `${current}->${val}` : `${val}`)
const aux = (node, currentPath = '', acc) => {
if (!node) {
return acc
}
if (isLeaf(node)) {
currentPath = join(currentPath, node.val)
acc.push(currentPath)
}
aux(node.left, join(currentPath, node.val), acc)
aux(node.right, join(currentPath, node.val), acc)
return acc
}
return aux(root, '', [])
}