LeetCode 112. 路径总和

题目描述

🔥 112. 路径总和

image-20230305212745418

image-20230305212737634

思路分析

思路描述

参考代码

1
2
3
4
5
6
7
8
9
func hasPathSum(root *TreeNode, targetSum int) bool {
	if root == nil {
		return false
	}
	if root.Left == nil && root.Right == nil && targetSum == root.Val {
		return true
	}
	return hasPathSum(root.Left, targetSum-root.Val) || hasPathSum(root.Right, targetSum-root.Val)
}
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 hasPathSum(root *TreeNode, targetSum int) bool {
	if root == nil {
		return false
	}
	queue := []*TreeNode{root}
	for len(queue) > 0 {
		size := len(queue)
		for i := 0; i < size; i++ {
			node := queue[i]
			if node.Left == nil && node.Right == nil && node.Val == targetSum {
				return true
			}
			if node.Left != nil {
				node.Left.Val += node.Val
				queue = append(queue, node.Left)
			}
			if node.Right != nil {
				node.Right.Val += node.Val
				queue = append(queue, node.Right)
			}
		}
		queue = queue[size:]
	}
	return false
}

🍏 点击查看 Java 题解

1
write your code here

相似题目

题目 难度 题解
路径总和 II Medium  
二叉树中的最大路径和 Hard  
求根节点到叶节点数字之和 Medium  
路径总和 III Medium  
路径总和 IV Medium  
本文作者:
本文链接: https://hgnulb.github.io/blog/60277569
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!