问题:
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>) {
}
有问题随时沟通
网友评论