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
}
相关推荐
炘爚3 分钟前
LeetCode(两两交换链表中的节点)
算法·leetcode·链表
wsoz3 分钟前
Leetcode矩阵-day7
c++·算法·leetcode·矩阵
不想看见4044 分钟前
Merge k Sorted Lists 优先队列--力扣101算法题解笔记
笔记·算法·leetcode
_深海凉_6 分钟前
LeetCode热题100-合并区间
算法·leetcode·职场和发展
6Hzlia7 分钟前
【Hot 100 刷题计划】 LeetCode 79. 单词搜索 | C++ 标准方向数组 DFS 与回溯
c++·leetcode·深度优先
abant240 分钟前
leetcode 76 最小覆盖子串
算法·leetcode·职场和发展
田梓燊44 分钟前
leetcode 240
算法·leetcode·职场和发展
We་ct1 小时前
LeetCode 149. 直线上最多的点数:题解深度剖析
前端·javascript·算法·leetcode·typescript
sheeta19981 小时前
LeetCode 每日一题笔记 日期:2026.04.13 题目:1848.到目标元素的最小距离
笔记·算法·leetcode
Tisfy1 小时前
LeetCode 1848.到目标元素的最小距离:数组遍历(附python一行版)
python·leetcode·题解·遍历