問題: A binary tree is univalued if every node in the tree has the same value. Return true if and only if the given tree is univalued.
方法: 先儲存根節點的val,然後遞迴遍歷整個tree,如果有某個節點的val不等於根節點的val則返回false,否則返回true,遍歷的結果即為最終結果。
具體實現:
class UnivaluedBinaryTree {
// Definition for a binary tree node.
class TreeNode(var `val`: Int = 0) {
var left: TreeNode? = null
var right: TreeNode? = null
}
private var uniValue = 0
fun isUnivalTree(root: TreeNode?): Boolean {
if(root == null) {
return false
} else {
uniValue = root.`val`
return isUnivalTreeInternal(root.left) && isUnivalTreeInternal(root.right)
}
}
fun isUnivalTreeInternal(root: TreeNode?): Boolean {
if(root == null) {
return true
} else {
return isUnivalTreeInternal(root.left) && isUnivalTreeInternal(root.right) && root.`val` == uniValue
}
}
}
fun main(args: Array<String>) {
}
複製程式碼
有問題隨時溝通