Golang | Leetcode Golang题解之第113题路径总和II

题目:

题解:

Go 复制代码
type pair struct {
    node *TreeNode
    left int
}

func pathSum(root *TreeNode, targetSum int) (ans [][]int) {
    if root == nil {
        return
    }

    parent := map[*TreeNode]*TreeNode{}

    getPath := func(node *TreeNode) (path []int) {
        for ; node != nil; node = parent[node] {
            path = append(path, node.Val)
        }
        for i, j := 0, len(path)-1; i < j; i++ {
            path[i], path[j] = path[j], path[i]
            j--
        }
        return
    }

    queue := []pair{{root, targetSum}}
    for len(queue) > 0 {
        p := queue[0]
        queue = queue[1:]
        node := p.node
        left := p.left - node.Val
        if node.Left == nil && node.Right == nil {
            if left == 0 {
                ans = append(ans, getPath(node))
            }
        } else {
            if node.Left != nil {
                parent[node.Left] = node
                queue = append(queue, pair{node.Left, left})
            }
            if node.Right != nil {
                parent[node.Right] = node
                queue = append(queue, pair{node.Right, left})
            }
        }
    }

    return
}
相关推荐
灯澜忆梦1 小时前
GO---可见性规则
开发语言·golang
怪兽学LLM3 小时前
LeetCode 105. 从前序与中序遍历序列构造二叉树:分治递归思路详解
算法·leetcode·职场和发展
退休倒计时4 小时前
【每日一题】LeetCode 39. 组合总和 TypeScript
算法·leetcode·typescript
qz5zwangzihan16 小时前
题解:Atcoder Beginner Contest abc466 F - Many Mod Calculation
c++·题解·优先队列·atcoder·大根堆·abc466·abc466f
兰令水6 小时前
hot100【acm版】【2026.7.13打卡-java版本】
java·开发语言·数据结构·算法·leetcode·面试
Tisfy6 小时前
LeetCode 1291.顺次数:打表/枚举
算法·leetcode·题解·枚举·遍历
tiana_7 小时前
写了个零依赖的 Go 版本管理器,curl | bash 完事
开发语言·golang·bash
罗超驿7 小时前
双指针算法详解:从入门到精通(Java版)
算法·leetcode·职场和发展
tkevinjd8 小时前
力扣300-最长递增子序列
算法·leetcode·职场和发展·动态规划·贪心
灯澜忆梦9 小时前
GO---map函数
开发语言·前端·后端·golang