Skip to content

257. 二叉树的所有路径

js
;(function () {
  /**
   * 257. 二叉树的所有路径
   * 给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
   * 说明: 叶子节点是指没有子节点的节点。
   *
   * 输入:root = [1,2,3,null,5]
   * 输出:["1->2->5","1->3"]
   *
   */
  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 binaryTreePaths(root: TreeNode | null): string[] {
    // 方法一:
    // let res: string[][] = [];
    // let pre: string[] = [];
    // let rootKey: string = ''
    // if (!root) {
    //     return []
    // } else {
    //     rootKey = String(root.val);
    // }
    // function presort(root: TreeNode | null) {
    //     if (!root) return
    //     pre.push(String(root.val));
    //     presort(root.left)
    //     presort(root.right)
    //     if (!root.left && !root.right) {
    //         res.push([...pre])
    //         pre.pop()
    //     }
    // }
    // presort(root)
    // return res.map(i => i.join('->'))

    // 方法二: 深度优先
    const paths: string[] = []
    const construct_paths = (root: TreeNode | null, path: string) => {
      if (root) {
        path += root.val.toString()
        if (root.left === null && root.right === null) {
          // 当前节点是叶子节点
          paths.push(path) // 把路径加入到答案中
        } else {
          path += '->' // 当前节点不是叶子节点,继续递归遍历
          construct_paths(root.left, path)
          construct_paths(root.right, path)
        }
      }
    }
    construct_paths(root, '')
    return paths

    // 方法三: 广度优先
  }
})()