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
}
相关推荐
Nil2086 分钟前
leetcode 199二叉树的右视图
算法·leetcode·深度优先
敢敢のwings3 小时前
智元 GO-2 与 AgiBot-World 深度解读
开发语言·后端·golang
FfHUCisI3 小时前
Golang 数据库连接池深度调优
android·数据库·golang
程序员小八7774 小时前
Java 快速转 Go
java·python·golang
土司大王4 小时前
LeetCode hot100——两两交换链表中的节点
算法·leetcode·职场和发展
zander2586 小时前
LeetCode 300. 最长递增子序列
算法·leetcode·深度优先
欧叶冲冲冲6 小时前
Python常见数据结构的CRUD(LeetCode高频版速查)
数据结构·python·leetcode
名字还没想好☜7 小时前
Go 用 slices/maps 标准库泛型函数:告别手写 Contains、Sort、去重(Go 1.21)
开发语言·后端·算法·golang·go
圣保罗的大教堂7 小时前
leetcode 3622. 判断整除性 简单
leetcode
Lyyaoo.8 小时前
【普通数组】【中等】除了自身以外数组的乘积
数据结构·算法·leetcode