Recca Chao 的 gitHub page

推廣網站開發,包含 Laravel 和 Kotlin 後端撰寫、自動化測試、讀書心得等。Taiwan Kotlin User Group 管理員。

View on GitHub

Kotlin Leetcode - 404. Sum of Left Leaves

題目連接

class Solution {
    fun sumOfLeftLeaves(root: TreeNode?): Int {
    }
}

解題思路

這題測試的是對樹的遍歷

利用遞迴可以很快的做出這一題

Kotlin 參考解答

點擊展開解答

一樣可以寫成單個表達式

注意這邊要標注回傳型態

class Solution {
    fun sumOfLeftLeaves(root: TreeNode?): Int =
        when {
            root == null -> 0
            root.left != null && root.left.left == null && root.left.right == null
            -> root.left.`val` + sumOfLeftLeaves(root.right)
            else -> sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right)
        }
}

回到 leetcode 列表