go 刷算法第三题——二叉树根节点到叶子节点和为指定值的路径

描述

image

思路

穷举所有叶子节点,判断是否满足条件。

go代码

package main
import "fmt"
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func demo(root *TreeNode, sum int, path []int, result *[][]int) {
if root.Left != nil {
demo(root.Left, sum-root.Val, append(path, root.Val), result)
}
if root.Right != nil {
demo(root.Right, sum-root.Val, append(path, root.Val), result)
}
// 为叶子节点,递归结束。判断 root.Val == sum
if root.Left == nil && root.Right == nil && root.Val == sum {
// 由于闭包的原因,在root.Val==A的时候,A的右子节点递归与A的左子节点递归传递的path是同一个引用地址。
// *result = append(*result, append(path, sum))
tmp := make([]int, len(path)+1)
copy(tmp, append(path, sum))
*result = append(*result, tmp)
}
}
func pathSum(root *TreeNode, sum int) [][]int {
if root == nil {
return nil
}
result := make([][]int, 0)
path := make([]int, 0)
demo(root, sum, path, &result)
fmt.Println(result)
return result
}
func main() {
//node := TreeNode{1, &TreeNode{2, nil, nil}, nil}
node := TreeNode{1, nil, nil}
sum := pathSum(&node, 1)
fmt.Println(sum)
}
posted @   临渊不羡渔  阅读(79)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示