LeetCode讲解篇之113. 路径总和 II

文章目录

  • 题目描述
  • 题解思路
  • 题解代码

题目描述

LeetCode讲解篇之113. 路径总和 II_第1张图片

题解思路

深度优先遍历二叉树,遍历的同时记录路径,直到遍历到叶节点,若路径和为targetSum则添加到结果集中

题解代码

func pathSum(root *TreeNode, targetSum int) [][]int {
    var res = make([][]int, 0)
    path := make([]int, 0, 1)
    var sum func(root *TreeNode, targetSum int)
    sum = func (root *TreeNode, targetSum int) {
        if root == nil {
            return
        }
        targetSum -= root.Val
        path = append(path, root.Val)
        defer func() { path = path[:len(path)-1] }()
        if root.Left == nil && root.Right == nil && targetSum == 0 {
            res = append(res, append([]int{}, path...))
            return
        }
        sum(root.Left, targetSum)
        sum(root.Right, targetSum)
    }
    sum(root, targetSum)
    return res
}

你可能感兴趣的:(数据结构与算法,深度优先,算法)