LeetCode之Path Sum II(Kotlin)

2020-06-15  本文已影响0人  糕冷羊

问题:



方法:
回溯法加DFS,在遇到叶子节点时判断路径是否符合要求。

class PathSumII {
    fun pathSum(root: TreeNode?, sum: Int): List<List<Int>> {
        val result = mutableListOf<List<Int>>()
        if (root != null) {
            val list = mutableListOf<Int>()
            dfs(root, list, result, sum)
        }
        return result
    }

    private fun dfs(root: TreeNode, list: MutableList<Int>, lists: MutableList<List<Int>>, sum: Int) {
        val new = mutableListOf<Int>()
        new.addAll(list)
        new.add(root.`val`)
        if (root.left == null && root.right == null) {
            if (new.sum() == sum) {
                lists.add(new)
            }
        } else {
            root.left?.let { dfs(it, new, lists, sum) }
            root.right?.let { dfs(it, new, lists, sum) }
        }
    }
}

fun main(args: Array<String>) {

}

有问题随时沟通

具体代码实现可以参考Github

上一篇 下一篇

猜你喜欢

热点阅读