Recca Chao 的 gitHub page

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

View on GitHub

Kotlin Leetcode - 617. Merge Two Binary Trees

題目連接:https://leetcode.com/problems/merge-two-binary-trees/

/**
 * Example:
 * var ti = TreeNode(5)
 * var v = ti.`val`
 * Definition for a binary tree node.
 * class TreeNode(var `val`: Int) {
 *     var left: TreeNode? = null
 *     var right: TreeNode? = null
 * }
 */
class Solution {
    fun mergeTrees(root1: TreeNode?, root2: TreeNode?): TreeNode? {
        
    }
}

解題思路

這一題考的是樹的處理

雖然有一點點複雜

不過一樣可以以遞迴處理

透過 scope function 和 when

可以將這段邏輯以單一表達式解決

Kotlin 參考解答

搭配 scope function 和 when

以單一表達式解決的方式如下

class Solution {
    fun mergeTrees(t1: TreeNode?, t2: TreeNode?): TreeNode? {
        return when {
            t1 == null -> t2
            t2 == null -> t1
            else -> t1.apply {
                `val` += t2.`val`
                left = mergeTrees(left, t2.left)
                right = mergeTrees(right, t2.right)
            }
        }
    }
}

回到 leetcode 列表