Leetcode Simple Solutions


A set of simple solutions to remind me how easy it can be.

JavaScript 100% | Simple DFS / Backtracking Solution

Solution: https://leetcode.com/problems/binary-tree-paths


/**
* @param {TreeNode} root
* @return {string[]}
*/
var binaryTreePaths = function (root, paths = [], path = []) {
path.push(root.val)
if (!root.right && !root.left) paths.push(path.join('->')); // join paths at the end of the three leafs

root.left && binaryTreePaths(root.left, paths, path);
root.right && binaryTreePaths(root.right, paths, path);

path.pop(); // reverse paths going back the reccursion

return paths;
};

Output
["1->2->5","1->3"]

Solution Source