Binary Tree Paths
You're given the root of a binary tree. Return every path that starts at the root and ends at a leaf, formatted as a string with -> joining the node values, in any order.
Input Format
Implement binaryTreePaths(root). Inputs below show JavaScript function arguments; there is no stdin parsing.
Trees use level-order arrays with null for missing children. The editor passes nodes with val, left, and right properties; [] becomes null.
Output Format
Return the result described in the statement.
The order of the outer result array does not matter.
Sample Input and Output
Example 1 · Run Sample
Input
root = [1,2,3,null,5] Output
["1->2->5","1->3"] Example 2
Input
root = [1] Output
["1"] Constraints
- 1 <= number of nodes <= 100
- -100 <= Node.val <= 100
Test Cases (2)
Case 1
Args: [[1,2,3,null,5]]
Expected: ["1->2->5","1->3"]
Case 2
Args: [[1]]
Expected: ["1"]
Topics
DFS with Path Tracking
function binaryTreePaths(root) {
const result = [];
function dfs(node, path) {
if (!node) return;
path += node.val;
if (!node.left && !node.right) { result.push(path); return; }
dfs(node.left, path + '->');
dfs(node.right, path + '->');
}
dfs(root, '');
return result;
}Time: O(n × h) as a loose upper bound for path strings, where h is tree height | Space: O(h²) auxiliary string storage in the worst case, excluding output
Saved in this browser only. Private to you.