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

%% Definition for a binary tree node.
%%
%% -record(tree_node, {val = 0 :: integer(),
%%                     left = null  :: 'null' | #tree_node{},
%%                     right = null :: 'null' | #tree_node{}}).

-spec is_valid_bst(Root :: #tree_node{} | null) -> boolean().
is_valid_bst(Tree) ->
   is_valid_bst(null, Tree,  null).

in_range(null, Middle, null) ->
    true;

in_range(Min, Middle, null) ->
    Min < Middle;

in_range(null, Middle, Max) ->
    Middle < Max;

in_range(Min, Middle, Max) ->
    (Min < Middle) and (Middle < Max).

is_valid_bst(Min, null, Max) ->
    true;
is_valid_bst(Min, #tree_node{val = Val, left = Left, right = Right}, Max) ->
    in_range(Min, Val, Max) andalso
            is_valid_bst(Min, Left, Val) andalso 
                is_valid_bst(Val, Right, Max).