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
}
相关推荐
ん贤2 小时前
Go channel 深入解析
开发语言·后端·golang
逆境不可逃7 小时前
LeetCode 热题 100 之 64. 最小路径和 5. 最长回文子串 1143. 最长公共子序列 72. 编辑距离
算法·leetcode·动态规划
yashuk7 小时前
Go-Gin Web 框架完整教程
前端·golang·gin
Eward-an9 小时前
LeetCode 239. 滑动窗口最大值(详细技术解析)
python·算法·leetcode
一叶落4389 小时前
LeetCode 50. Pow(x, n)(快速幂详解 | C语言实现)
c语言·算法·leetcode
x_xbx10 小时前
LeetCode:26. 删除有序数组中的重复项
数据结构·算法·leetcode
j_xxx404_12 小时前
力扣困难算法精解:串联所有单词的子串与最小覆盖子串
java·开发语言·c++·算法·leetcode·哈希算法
big_rabbit050212 小时前
[算法][力扣167]Two Sum II
算法·leetcode·职场和发展
Eward-an13 小时前
LeetCode 76. 最小覆盖子串(详细技术解析)
python·算法·leetcode·职场和发展
不想看见40413 小时前
Reverse Bits位运算基础问题--力扣101算法题解笔记
笔记·算法·leetcode