LeetCode 257. 二叉树的所有路径

题目描述

257. 二叉树的所有路径

image-20250418205204011

思路分析

  1. 递归遍历:使用深度优先搜索遍历二叉树,从根节点开始,沿着每条路径向下递归。
  2. 路径记录:在递归过程中,记录当前路径上的节点值。
  3. 路径拼接:当到达叶子节点时,将当前路径拼接成字符串并加入结果集中。
  4. 回溯:在递归返回时,移除当前节点值,回溯到上一个节点,继续搜索其他路径。

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func binaryTreePaths(root *TreeNode) []string {
	var res []string

	var dfs func(node *TreeNode, path string)
	dfs = func(node *TreeNode, path string) {
		if node == nil {
			return
		}

		// 如果是叶子节点,则路径完成
		if node.Left == nil && node.Right == nil {
			res = append(res, path+strconv.Itoa(node.Val))
			return
		}

		// 继续向下遍历左右子树
		path += strconv.Itoa(node.Val) + "->"
		dfs(node.Left, path)
		dfs(node.Right, path)
	}

	dfs(root, "")
	return res
}
  • 时间复杂度:O(n),其中 n 是节点个数。
  • 空间复杂度:O(h),其中 h 是树的高度。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
func binaryTreePaths(root *TreeNode) []string {
    var res []string
    var dfs func(cur *TreeNode, path string)
    dfs = func(cur *TreeNode, path string) {
        if cur == nil {
            return
        }
        // 将当前节点的值添加到路径中
        if path == "" {
            path = strconv.Itoa(cur.Val)
        } else {
            path += "->" + strconv.Itoa(cur.Val)
        }
        // 如果是叶子节点,添加路径到结果中
        if cur.Left == nil && cur.Right == nil {
            res = append(res, path)
        } else {
            // 继续遍历左子树和右子树
            dfs(cur.Left, path)
            dfs(cur.Right, path)
        }
    }
    dfs(root, "")
    return res
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
func binaryTreePaths(root *TreeNode) []string {
	var res []string
	var path []string

	var dfs func(node *TreeNode)
	dfs = func(node *TreeNode) {
		if node == nil {
			return
		}

		// 将当前节点值加入路径
		path = append(path, strconv.Itoa(node.Val))

		// 判断是否到达叶子节点
		if node.Left == nil && node.Right == nil {
			// 将当前路径拼接成字符串并加入结果集
			res = append(res, strings.Join(path, "->"))
		} else {
			// 递归遍历左子树和右子树
			dfs(node.Left)
			dfs(node.Right)
		}

		// 回溯,移除当前节点值
		path = path[:len(path)-1]
	}

	dfs(root)
	return res
}
  • 时间复杂度:O (n),其中 n 是树中节点的数量。
  • 空间复杂度:O (h),其中 h 是树的高度。

➡️ 点击查看 Java 题解

1
write your code here
本文作者:
本文链接: https://hgnulb.github.io/blog/2025/53054646
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!