首页 > 其他 > 详细

113. Path Sum II

时间:2020-05-12 09:07:23      阅读:49      评论:0      收藏:0      [点我收藏+]
package LeetCode_113

/**
 * 113. Path Sum II
 * https://leetcode.com/problems/path-sum-ii/description/
 * 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]
]
 * */

class TreeNode(var `val`: Int) {
    var left: TreeNode? = null
    var right: TreeNode? = null
}

class Solution {
    val result = ArrayList<List<Int>>()
    fun pathSum(root: TreeNode?, sum: Int): List<List<Int>> {
        if (root == null) {
            return result
        }
        dfsWithList(root, ArrayList(), 0, sum)
        return result
    }

    private fun dfsWithList(root: TreeNode?, list: ArrayList<Int>, currentSum: Int, target: Int) {
        if (root==null){
            return
        }
        list.add(root.`val`)
        if (root.left == null && root.right == null) {
            if (currentSum+root.`val`==target){
                result.add(ArrayList<Int>(list))
            }
        }
        dfsWithList(root.left,list,currentSum+root.`val`,target)
        dfsWithList(root.right,list,currentSum+root.`val`,target)
        //because is backtracking, so need reset the list for next result
        list.removeAt(list.size-1)
    }
}

 

113. Path Sum II

原文:https://www.cnblogs.com/johnnyzhao/p/12873444.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!