Binary Tree Paths Easy 0 attempts
LeetCode ↗

Binary Tree Paths

Easy TreeBinary TreeDFS LeetCode

Given the root of a binary tree, return all root-to-leaf paths in any order.

Example: root = [1,2,3,null,5] → Output: ["1->2->5", "1->3"]

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

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) | Space: O(n)

Saved in this browser only. Private to you.

JavaScript