Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
/**
* 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) {
if (!root) {
return [];
}
const result = [];
function traverse(node, path = []) {
let newPath = [];
if (node.left) {
newPath = path.slice(0);
newPath.push(node.val);
traverse(node.left, newPath);
}
if (node.right) {
newPath = path.slice(0);
newPath.push(node.val);
traverse(node.right, newPath);
}
if (!node.left && !node.right) {
path.push(node.val);
result.push(path.join('->'));
}
}
traverse(root);
return result;
};