黄哥Python: LeetCode 113题 Path Sum II 解题思路

189 阅读1分钟
原文链接: zhuanlan.zhihu.com

113.Path Sum II

Loading...leetcode.com图标

1、 先读题,题目是求从根到叶子node,路径上所有数字之和等于sum 的所有路径。

2、先求出从root 到叶子node,所有路径的二维数组,再判断二维数组中那些元素之和等于sum值。

3、用递归深度优先搜索解决,用一个二维数组统计所有路径,一个一维数组保存每一条路径。

4、当到达叶子节点时,将一维数组保存的路径添加到二维数组中。

请看黄哥所写的Python 代码和Go 语言代码。

Python 代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
# 黄哥Python培训 黄哥所写
class Solution:
    def pathSum(self, root: TreeNode, s: int) -> List[List[int]]:
        if root is None:
            return []
        paths = []
        def dfs(root, nodes):
            if root is None:
                return
            nodes.append(root.val)
            if root.left is None and root.right is None:
                paths.append(nodes)
            dfs(root.left, nodes[:])
           
            dfs(root.right, nodes[:])
           
        dfs(root, [])
        return [item for item in paths if sum(item) == s]

Go 代码

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
//  黄哥Python培训 黄哥所写
func pathSum(root *TreeNode, sum int) [][]int {
    if root == nil {
        return [][]int{}
    }
    var paths, res [][]int
    path := []int{}
    dfs(root, path, &paths)
    for _, item := range paths {
        if sumSlice(item) == sum {
            res = append(res, item)
        }
    }
    return res
}

func dfs(root *TreeNode, path []int, paths *[][]int) {
    if root == nil {
        return 
    }
    path = append(path, root.Val)
    if root.Left == nil && root.Right == nil {
        copy := append(make([]int, 0, len(path)), path...)
        *paths = append(*paths, copy)   
        
    }
    dfs(root.Left, path, paths)
    
    dfs(root.Right, path, paths)
}

func sumSlice(arr []int) int{
    res := 0
    for _, item := range arr {
        res += item
    }
    return res
    
}
黄哥:黄哥Python:提醒要转行当程序员的朋友,学习要分先后主次zhuanlan.zhihu.com图标黄哥:黄哥Python培训是这样训练学员的zhuanlan.zhihu.com图标