257. Binary Tree Paths

Description

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1
 /   \
2     3
 \
  5

All root-to-leaf paths are:

["1->2->5", "1->3"]

Solution

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * Traverse the binary tree with Depth-First Search (DFS) algorithm (preorder)
 * @param {TreeNode} root
 * @return {string[]}
 */
var binaryTreePaths = function(root) {
    "use strict";
    if (!root) {
        return [];
    }
    let result = [];
    function dfs(node, path) {
        let str = `${path}${node.val}`;
        node.left && dfs(node.left, `${str}->`);
        node.right && dfs(node.right, `${str}->`);
        !node.left && !node.right && result.push(str);
    }
    dfs(root, "");
    return result;
};

results matching ""

    No results matching ""