Kotlin Leetcode - 617. 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 列表