Valid Binary Search Tree

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

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution {
    public bool IsValidBST(TreeNode root)
    {

        return validate(root, null, null);
    }
    public bool validate(TreeNode root, int? low, int? high)
    {
        if (root == null)
        {
            return true;
        }

        if ((low != null && root.val <= low) || (high != null && root.val >= high))
        {
            return false;
        }

        return validate(root.right, root.val, high) && validate(root.left, low, root.val);
    }
}

Let's analyze the time and space complexity of the given algorithm:

  • Time Complexity: The time complexity of this algorithm is O(n), where n is the number of nodes in the binary tree. This is because in the worst case, the algorithm needs to visit all the nodes of the tree to check if it's a valid BST.

  • Space Complexity: The space complexity of this algorithm is O(h), where h is the height of the binary tree. This is because the maximum amount of space used by the call stack during the recursive calls is equal to the height of the tree. In the worst case, when the tree is skewed, the height of the tree is equal to the number of nodes, so the space complexity would be O(n).

Last updated