「前端刷题」257.二叉树的所有路径(EASY)

87 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第11天,点击查看活动详情

题目(Binary Tree Paths)

链接:https://leetcode-cn.com/problems/binary-tree-paths
解决数:1705
通过率:70.4%
标签:树 深度优先搜索 字符串 回溯 二叉树 
相关公司:facebook amazon bytedance 

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

叶子节点 是指没有子节点的节点。

 

示例 1:

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

示例 2:

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

 

提示:

  • 树中节点的数目在范围 [1, 100] 内
  • -100 <= Node.val <= 100

思路

dfs

  • 思路:递归左右子树,直到叶子节点,递归的过程中不断透传path,递归的每一层连接上当前节点的值
  • 复杂度:时间复杂度O(n),每个节点遍历一次。空间复杂度O(n),递归栈空间

代码

var binaryTreePaths = function(root) {
    const paths = [];
    const dfs = (root, path) => {//传入递归的节点和路径数组
        if (root) {
            path += root.val.toString();//加入当前节点
          	//叶子结点就将所有连接起来的节点字符串加入paths中 也就是其中一条路径
            if (root.left === null && root.right === null) { 
                paths.push(path); 
            } else {
                path += "->"; //不是叶子节点继续递归左右子树
                dfs(root.left, path);
                dfs(root.right, path);
            }
        }
    }
    dfs(root, "");
    return paths;
};

bfs

动画过大,点击查看

  • 思路:用队列辅助进行广度优先遍历,不断将左右子节点加入队列,直到叶子节点
  • 复杂度:同方法1

代码

var binaryTreePaths = function(root) {
    const res = [];
    if (root === null) {
        return res;
    }
    const nodes = [root];
    const paths = [root.val.toString()];

    while (nodes.length) {
        const node = nodes.shift(); 
        const path = paths.shift();

        if (node.left === null && node.right === null) {//叶子节点
            res.push(path);
        } else {
            if (node.left !== null) {//左节点不为空 加入队列
                nodes.push(node.left);
                paths.push(path + "->" + node.left.val.toString());
            }

            if (node.right !== null) {//右节点不为空 加入队列
                nodes.push(node.right);
                paths.push(path + "->" + node.right.val.toString());
            }
        }
    }
    return res;
};

递归

代码

var recur = function (root, res, cur) {
    // 递归返回条件 1.  如果节点为空
    if (root === null) return
    // 递归返回条件 2.  如果节点为叶子节点 已经找到了一条路径
    if (root.left === null && root.right === null) {
        // 将路径存入数组
        cur += root.val
        res.push(cur)
        return
    } else {
        // 非叶子节点 加’->‘表示
        cur += root.val + '->'

    }
    // 递归左右子树
    recur(root.left, res, cur)
    recur(root.right, res, cur)
}
var binaryTreePaths = function(root) {
    // 如果根节点为空 直接返回
    if (root === null) return []
    let res = [],cur = ''
    // 递归
    recur(root, res,cur)
    return res
};