问题: 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.node
方法: 先保存根节点的val,而后递归遍历整个tree,若是有某个节点的val不等于根节点的val则返回false,不然返回true,遍历的结果即为最终结果。git
具体实现:github
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>) {
}
复制代码
有问题随时沟通bash