All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0901_1000.s0965_univalued_binary_tree.Solution.kt Maven / Gradle / Ivy

There is a newer version: 1.28
Show newest version
package g0901_1000.s0965_univalued_binary_tree

// #Easy #Depth_First_Search #Breadth_First_Search #Tree #Binary_Tree
// #2023_05_05_Time_138_ms_(90.91%)_Space_35.2_MB_(9.09%)

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 = LinkedList()
        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
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy