> Uploading knowledge... _
[░░░░░░░░░░░░░░░░░░░░░░░░] 0%
blog logo
> CHICIO CODING_Pixels. Code. Unplugged.

Binary Tree Paths

Leetcode Problem 257: Binary Tree Paths

Problem Summary

Given the root of a binary tree, return all root-to-leaf paths in any order. A leaf is a node with no children. Each path should be represented as a string of node values joined by "->".

Constraints:

  • The tree has between 1 and 100 nodes.
  • Node values are integers in the range [-100, 100].

Techniques

  • String
  • Backtracking
  • Tree
  • Depth-First Search
  • Binary Tree

Solution

export class TreeNode {
    val: number
    left: TreeNode | null
    right: TreeNode | null

    constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
        this.val = (val === undefined ? 0 : val)
        this.left = (left === undefined ? null : left)
        this.right = (right === undefined ? null : right)
    }
}

function binaryTreePathsRecursive(root: TreeNode | null, rootToLeafs: string[], path: string) {
    if (!root) {
        return
    }

    if (!root.left && !root.right) {
        rootToLeafs.push(`${path}${root.val}`)
        return
    }

    binaryTreePathsRecursive(root.left, rootToLeafs, `${path}${root.val}->`)
    binaryTreePathsRecursive(root.right, rootToLeafs, `${path}${root.val}->`)
}

function binaryTreePaths(root: TreeNode | null): string[] {
    const rootToLeafs: string[] = []
    binaryTreePathsRecursive(root, rootToLeafs, "")
    return rootToLeafs
};