LeetCode-in-All

98. Validate Binary Search Tree

Medium

Given the root of a binary tree, determine if it is a valid binary search tree (BST).

A valid BST is defined as follows:

Example 1:

Input: root = [2,1,3]

Output: true

Example 2:

Input: root = [5,1,4,null,null,3,6]

Output: false

Explanation: The root node’s value is 5 but its right child’s value is 4.

Constraints:

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 isValidBST(root: TreeNode?): Boolean {
        return solve(root, Long.MIN_VALUE, Long.MAX_VALUE)
    }

    // we will send a valid range and check whether the root lies in the range
    // and update the range for the subtrees
    private fun solve(root: TreeNode?, left: Long, right: Long): Boolean {
        if (root == null) {
            return true
        }
        return if (root.`val` <= left || root.`val` >= right) {
            false
        } else solve(root.left, left, root.`val`.toLong()) && solve(root.right, root.`val`.toLong(), right)
    }
}