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
}
相关推荐
何以解忧,唯有..6 天前
Go语言循环语句详解:for、range与循环控制
开发语言·算法·golang
踏着七彩祥云的小丑6 天前
Go学习第9天:并发编程 + 文件操作 + 正则表达式
学习·golang·正则表达式·go
想吃火锅10056 天前
【leetcode】121.买卖股票的最佳时机js/c++
算法·leetcode·职场和发展
JCGKS6 天前
Go `init` 函数:包初始化顺序到底是怎样的
golang·init·init执行顺序
何以解忧,唯有..6 天前
Go语言中的const:常量声明与iota枚举详解
java·开发语言·golang
凌波粒6 天前
LeetCode--491.递增子序列(回溯算法)
数据结构·算法·leetcode
退休倒计时6 天前
【每日一题】LeetCode 146. LRU 缓存 TypeScript
算法·leetcode·缓存·typescript
小欣加油6 天前
leetcode3612 用特殊操作处理字符串I
数据结构·c++·算法·leetcode·职场和发展
凌波粒6 天前
LeetCode--90.子集II(回溯算法)
数据结构·算法·leetcode
凌波粒6 天前
LeetCode--46.全排列(回溯算法)
数据结构·算法·leetcode