LeetCode之Sum of Left Leaves(Kotlin)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wanglikun7342/article/details/78993989

问题:
Find the sum of all left leaves in a given binary tree.

  3
 / \
9  20
  /  \
 15   7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.


方法:
递归实现,遍历所有叶节点,递归时增加是否为左子树参数,如果既为左子树且同时是叶子节点则返回节点值,对所有符合条件节点的值求和即为结果。

具体实现:

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

    fun sumOfLeftLeaves(root: TreeNode?): Int {
        return sumOfLeftLeaves(root, false)
    }

    private fun sumOfLeftLeaves(root: TreeNode?, left: Boolean): Int {
        if (root == null) {
            return 0
        }
        if (root.left == null
                && root.right == null) {
            return if (left) {
                root.`val`
            } else {
                0
            }
        } else if (root.left == null) {
            return sumOfLeftLeaves(root.right, false)
        } else if (root.right == null) {
            return sumOfLeftLeaves(root.left, true)
        }
        return sumOfLeftLeaves(root.left, true) + sumOfLeftLeaves(root.right, false)
    }
}

fun main(args: Array<String>) {
    val root = SumOfLeftLeaves.TreeNode(5)
    root.left = SumOfLeftLeaves.TreeNode(3)
    root.right = SumOfLeftLeaves.TreeNode(6)
    (root.left)?.left = SumOfLeftLeaves.TreeNode(2)
    (root.left)?.right = SumOfLeftLeaves.TreeNode(4)
    (root.right)?.right = SumOfLeftLeaves.TreeNode(7)
    val sumOfLeftLeaves = SumOfLeftLeaves()
    val result = sumOfLeftLeaves.sumOfLeftLeaves(root)
    println("result $result")
}

有问题随时沟通

具体代码实现可以参考Github

猜你喜欢

转载自blog.csdn.net/wanglikun7342/article/details/78993989