LeetcodeMay 23, 2025

Binary Tree Paths

Hazrat Ali

Leetcode

leaf is a node with no children.

 

Example 1:

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

Example 2:

Input: root = [1]
Output: ["1"]


Solution
/**
 * @param {TreeNode} root
 * @return {string[]}
 */
const binaryTreePaths = root => {
  const helper = (node, path) => {
    if (!node) {
      return;
    }

    path.push(node.val);

    if (!node.left && !node.right) {
      result.push(path.join('->'));
    } else {
      helper(node.left, path);
      helper(node.right, path);
    }

    path.pop();
  };

  const result = [];
  helper(root, []);
  return result;
};



Comments