257.b+树的所有轨迹(javascript)257.BinaryTreePaths

原创
小哥 3年前 (2022-11-10) 阅读数 5 #大杂烩

给你一个二叉树的根节点。 root ,按 任意顺序 ,返回从根节点到叶节点的所有路径。

叶子节点 是没有子节点的节点。
Given the root of a binary tree, return all root-to-leaf paths in any order.

A leaf is a node with no children.

示例 1:

输入:root = [1,2,3,null,5]
输出:["1->2->5","1->3"]

示例 2:

输入:root = [1]
输出:["1"]

深度优先搜索

思想和算法

最直观的方法是使用深度优先搜索。当深度优先搜索遍历二叉树时,我们需要考虑当前节点及其子节点。

  • 如果当前节点不是叶节点,请在当前路径的末尾添加该节点,并继续递归遍历该节点的每个子节点。
  • 如果当前节点是叶节点,在当前路径的末尾添加节点后,我们将得到从根节点到叶节点的路径,并将路径添加到答案中。

这样,当我们遍历完整的二叉树时,我们得到了从根节点到叶节点的所有路径。

var binaryTreePaths = function (root) {
    let newList = []
    var treePaths = function (root, path) {
        if (root) {
            if (root.left == null && root.right == null) {//当前节点是叶节点
                path += root.val + ""
                newList.push(path)//将路径添加到答案
                return
            }
            path += root.val + "->"// 当前节点不是叶节点,请继续递归遍历。
            treePaths(root.left, path)
            treePaths(root.right, path)
        }
    };
    treePaths(root, "")
    return newList
};

leetcode: https://leetcode-cn.com/problems/binary-tree-paths/

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除