Kotlin Leetcode - 965. Univalued Binary Tree
/**
* 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 isUnivalTree(root: TreeNode?): Boolean {
}
}
解題思路
這一題考的是對樹的處理
和 100. Same Tree 一樣
可以單純的透過遞迴判斷
Kotlin 參考解答
點擊展開解答
class Solution {
fun isUnivalTree(root: TreeNode?): Boolean {
return (root == null)
|| (root.left == null || root.`val` == root.left.`val`)
&& (root.right == null || root.`val` == root.right.`val`)
&& isUnivalTree(root.left) && isUnivalTree(root.right)
}
}
上述邏輯也可以透過 when 來改寫
class Solution {
fun isUnivalTree(root: TreeNode?): Boolean {
return when {
root == null -> true
root.left != null && root.`val` != root.left.`val` -> false
root.right != null && root.`val` != root.right.`val` -> false
else -> isUnivalTree(root.left) && isUnivalTree(root.right)
}
}
}
回到 leetcode 列表