LeetCode 剑指 Offer 34. 二叉树中和为某一值的路径

题目描述

剑指 Offer 34. 二叉树中和为某一值的路径

image-20241107210715031

image-20250418222752874

image-20250418222828222

思路分析

思路描述

参考代码

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 pathTarget(root *TreeNode, target int) [][]int {
	var res [][]int
	var path []int

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

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

		// 如果是叶子节点且路径和等于目标值,加入结果
		if node.Left == nil && node.Right == nil && sum == 0 {
			res = append(res, append([]int{}, path...)) // 复制当前路径
		}

		// 继续遍历左右子树
		dfs(node.Left, sum)
		dfs(node.Right, sum)

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

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

➡️ 点击查看 Java 题解

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