Skip to problem
←

Binary Tree Paths

Easy 0 attempts

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.

Function contract

Implement binaryTreePaths(root). The runner converts the level-order input array into nodes with val, left, and right fields; [] becomes null.

Output: An array of root-to-leaf path strings joined with ->, in any order. A leaf has no children.

Example 1

Input
root = [1,2,3,null,5]
Output
["1->2->5","1->3"]

Example 2

Input
root = [1]
Output
["1"]
Visual Aid
Stop only at a leaf
1235Paths: 1 → 2 → 5 and 1 → 3

Nodes 5 and 3 are leaves. The path 1 → 2 is incomplete because 2 still has a child.

Constraints
  • 1 <= number of nodes <= 100
  • -100 <= Node.val <= 100

DFS with Path Tracking

javascript
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

Loading discussion…

Saved in this browser only. Private to you.

JavaScript