LeetCode in Kotlin

965. Univalued Binary Tree

Easy

A binary tree is uni-valued if every node in the tree has the same value.

Given the root of a binary tree, return true if the given tree is uni-valued, or false otherwise.

Example 1:

Input: root = [1,1,1,1,1,null,1]

Output: true

Example 2:

Input: root = [2,2,2,5,2]

Output: false

Constraints:

Solution

import com_github_leetcode.TreeNode
import java.util.LinkedList

/*
 * 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 {
        val `val`: Int = root!!.`val`
        val queue: LinkedList<TreeNode?> = LinkedList<TreeNode?>()
        queue.add(root)
        while (queue.isNotEmpty()) {
            val node: TreeNode? = queue.poll()
            if (node!!.`val` != `val`) {
                return false
            }
            if (node.left != null) {
                queue.add(node.left)
            }
            if (node.right != null) {
                queue.add(node.right)
            }
        }
        return true
    }
}