文章 224
评论 6
浏览 200762
Tree - 113. Path Sum II

Tree - 113. Path Sum II

113. Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \    / \
7    2  5   1

Return:

[
   [5,4,11,2],
   [5,8,4,5]
]

思路:

题目意思是求出所有根节点到叶子结点路径和为sum的结果。递归求解,找到叶子节点比较sum就可以

代码:

go:

/**

 * Definition for a binary tree node.

 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func pathSum(root *TreeNode, sum int) [][]int {
    var res [][]int
    if root == nil {
        return res
    }
    
    recursive(root, &res, []int{root.Val}, root.Val, sum)
    
    return res
}

func recursive(node *TreeNode, res *[][]int, incr []int, tempSum int, sum int) {
    if node.Left == nil && node.Right == nil {
        if tempSum == sum {
            *res = append(*res, incr)
        } 
    }
    
    if node.Left != nil {
        var incrLeft []int
        incrLeft = append(incrLeft, incr...)
        incrLeft = append(incrLeft,  node.Left.Val)
        recursive(node.Left, res, incrLeft, tempSum + node.Left.Val, sum)
    }
    
    if node.Right != nil {
        recursive(node.Right, res, append(incr, node.Right.Val), tempSum + node.Right.Val, sum)
    }
}

标题:Tree - 113. Path Sum II
作者:michael
地址:https://www.bitbo-liuyang.com/articles/2019/08/19/1566222474551.html

Nothing just happens, it's all part of a plan.

取消