DEV Community

codingpineapple
codingpineapple

Posted on

98. Validate Binary Search Tree

Description:

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

A valid BST is defined as follows:

The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.

Solution:

Time Complexity : O(n)
h = height of the tree
Space Complexity: O(h)

// Depth first search approach
var isValidBST = function(root, min = null, max = null) {
    // Base case
    if (!root) return true;        
    if (min!==null && root.val <= min.val) return false;
    if (max!==null && root.val >= max.val) return false;
    /// Verify the left and right subtrees are binary search trees.
    return isValidBST(root.left, min, root) && isValidBST(root.right, root, max);
};

Enter fullscreen mode Exit fullscreen mode

Top comments (0)