LeetCode in Kotlin

501. Find Mode in Binary Search Tree

Easy

Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it.

If the tree has more than one mode, return them in any order.

Assume a BST is defined as follows:

Example 1:

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

Output: [2]

Example 2:

Input: root = [0]

Output: [0]

Constraints:

Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).

Solution

import com_github_leetcode.TreeNode

/*
 * 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 findMode(root: TreeNode?): IntArray {
        var maxOccurTimes = 0
        var prevValue: Int? = null
        var prevOccurTime = 1
        val ans = hashSetOf<Int>()

        fun updateGlobal(currValue: Int) {
            if (currValue == prevValue) {
                prevOccurTime++
                when {
                    prevOccurTime == maxOccurTimes -> ans.add(currValue)
                    prevOccurTime > maxOccurTimes -> {
                        maxOccurTimes = prevOccurTime
                        ans.clear()
                        ans.add(currValue)
                    }
                }
            } else {
                prevOccurTime = 1
                prevValue = currValue
                if (maxOccurTimes <= 1) {
                    ans.add(currValue)
                }
            }
        }

        fun processInOrder(node: TreeNode? = root) {
            if (node != null) {
                node.left?.let { processInOrder(it) }
                updateGlobal(node.`val`)
                node.right?.let { processInOrder(it) }
            }
        }
        processInOrder()
        return ans.toIntArray()
    }
}