Skip to content

Latest commit

 

History

History
53 lines (45 loc) · 1 KB

257. 二叉树的所有路径.md

File metadata and controls

53 lines (45 loc) · 1 KB

给定一个二叉树,返回所有从根节点到叶子节点的路径。

说明: 叶子节点是指没有子节点的节点。

示例:

输入:

   1
 /   \
2     3
 \
  5

输出: ["1->2->5", "1->3"]

解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3

solution:

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {string[]}
 */
var binaryTreePaths = function(root) {
    if (root === null) return []
    function findWay (node, path, paths) {
        if (node !== null) {
            path += node.val
            if (node.left === null && node.right === null) {
                paths.push(path)
            } else {
                path += '->'
                findWay(node.left, path, paths)
                findWay(node.right, path, paths)
            }
        }
    }
    const paths = []
    findWay(root, '', paths)
    return paths
};