You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin递归求树节点和问题:根节点未与子节点求和

问题解决:递归计算树节点和的类型不匹配问题

你的代码存在两个核心问题导致类型不匹配:

  1. 函数treeSumR的参数root被声明为非空的TreeNode<Int>,但代码里却判断root == null,这在Kotlin中是无效的——非空类型变量不可能为null,编译器会直接报错。
  2. root.left?.let { treeSumR(it) }返回的是Int?类型(当左子节点为null时,表达式结果为null),而root.key是Int类型,Kotlin不允许直接将Int与Int?相加,这就是你遇到的类型不匹配问题。

修改后的代码:

class TreeNode<T>(var key: T){
    var left: TreeNode<T>? = null
    var right: TreeNode<T>? = null
}

fun treeSumR(root: TreeNode<Int>?): Int{
    if (root == null) return 0
    // 用 ?: 0 处理子节点为null的情况,将Int?转为Int
    val leftSum = root.left?.let { treeSumR(it) } ?: 0
    val rightSum = root.right?.let { treeSumR(it) } ?: 0
    return root.key + leftSum + rightSum
}

fun buildTree2(): TreeNode<Int>{
    val one = TreeNode(1)
    val two = TreeNode(2)
    val four = TreeNode(4)
    val eleven = TreeNode(11)
    val three = TreeNode(3)
    val four2 = TreeNode(4)

    three.left = eleven
    three.right = four
    eleven.left = four2
    eleven.right = two
    four.right = one

    return three
}

关键改动说明:

  • 将treeSumR的参数改为TreeNode<Int>?,允许传入null,这样root == null的判断就合理了,作为递归的终止条件。
  • 对root.left?.let { ... }和root.right?.let { ... }的结果用?: 0兜底,当子节点为null时,求和结果按0计算,确保类型统一为Int,可以和root.key正常相加。

内容的提问来源于stack exchange,提问作者OEThe11

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 10:16:05