美文网首页
LeetCode之Univalued Binary Tree(K

LeetCode之Univalued Binary Tree(K

作者: 糕冷羊 | 来源:发表于2019-01-28 18:08 被阅读0次

问题:
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>) {

}

有问题随时沟通

具体代码实现可以参考Github

相关文章

网友评论

      本文标题:LeetCode之Univalued Binary Tree(K

      本文链接:https://www.haomeiwen.com/subject/apfzjqtx.html