Taro Logo

Validate Binary Search Tree

#94 Most AskedMedium
0 views
Topics:
TreesRecursion

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.

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:

  • The number of nodes in the tree is in the range [1, 104].
  • -231 <= Node.val <= 231 - 1

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Are duplicate values allowed in the binary search tree, and if so, must they strictly belong to one side (e.g., strictly less/greater) or can they be on either?
  2. What is the range of node values we can expect? Are they standard 32-bit signed integers, or could they span the full limits of integer types requiring special handling for infinity bounds?
  3. Can the tree be empty (i.e., is the root null), and if so, should an empty tree be considered a valid BST?
  4. Can the tree contain only a single node, and how should that be handled?
  5. Are the node values strictly integers, or could they be floating-point numbers or other comparable types?

Brute Force Solution

Approach

To check if a family tree of numbers follows the strict rule where every descendant on the left is smaller and every descendant on the right is larger, the brute force approach is to inspect every single person in the tree and check all of their relatives. We do this by exhaustively looking at every node and comparing it against every single one of its descendants to make sure no one is breaking the rule.

Here's how the algorithm would work step-by-step:

  1. Pick the very first person at the top of the tree as your starting point.
  2. Look at every single person located anywhere down the left side branch from your current position.
  3. Verify that every single one of those left-side descendants has a smaller number than the person you started with.
  4. Next, look at every single person located anywhere down the right side branch from your current position.
  5. Verify that every single one of those right-side descendants has a larger number than the person you started with.
  6. If any person on the left is larger or any person on the right is smaller, immediately conclude that the tree is invalid.
  7. If everyone on both sides follows the rule, move on to the next person in the tree and repeat the entire checking process for them.
  8. Continue this exhaustive inspection for every single person in the entire tree until you are completely certain no rules are broken anywhere.

Code Implementation

class TreeNode:
    def __init__(self, value=0, left_node=None, right_node=None):
        self.val = value
        self.left = left_node
        self.right = right_node

class Solution:
    def collect_all_descendants(self, current_node, collected_values):
        if current_node is None:
            return
            
        collected_values.append(current_node.val)
        self.collect_all_descendants(current_node.left, collected_values)
        self.collect_all_descendants(current_node.right, collected_values)

    def is_valid_bst(self, root_node: TreeNode) -> bool:
        if root_node is None:
            return True
            
        nodes_to_visit = [root_node]
        
        # We must evaluate every single node in the tree against its entire descendant tree
        while len(nodes_to_visit) > 0:
            current_person = nodes_to_visit.pop(0)
            
            left_descendant_values = []
            self.collect_all_descendants(current_person.left, left_descendant_values)
            
            # Every descendant on the left branch must be strictly smaller than the current root
            for left_value in left_descendant_values:
                if left_value >= current_person.val:
                    return False
            
            right_descendant_values = []
            self.collect_all_descendants(current_person.right, right_descendant_values)
            
            # Every descendant on the right branch must be strictly larger than the current root
            for right_value in right_descendant_values:
                if right_value <= current_person.val:
                    return False
            
            if current_person.left is not None:
                nodes_to_visit.append(current_person.left)
                
            if current_person.right is not None:
                nodes_to_visit.append(current_person.right)
                
        # If all nodes satisfy the BST constraints across all checks, the tree is valid
        return True

Big(O) Analysis

Time Complexity
O(n²) – To evaluate the binary tree using this brute force approach, we visit every single one of the n nodes in the tree as a starting point. For each individual node, we must exhaustively traverse and check all of its descendants located anywhere down its left and right subtrees. Because a node near the top may require inspecting a large portion of the tree, visiting n nodes and checking all their respective descendants results in roughly n * (n - 1) / 2 total comparison operations in the worst case. Simplifying this total by dropping constants and lower-order terms yields a final time complexity of O(n²).
Space Complexity
O(n) – The space complexity is driven by the recursive calls made during the exhaustive inspection of every single person in the tree. In the worst-case scenario where the tree is completely skewed like a linked list, these recursive calls accumulate on the call stack up to a maximum depth of N, where N is the total number of nodes in the tree. Because we store a stack frame for every node along this path, the auxiliary memory scales linearly with the input size N. Thus, the total extra memory simplifies in Big O notation to O(n).

Optimal Solution

Approach

To check if a tree is a valid binary search tree, the best approach is to walk through it while keeping track of the allowed range of values for every branch. As we move deeper into the tree, we narrow these boundary limits based on the decisions made at each turn to ensure no rule is broken.

Here's how the algorithm would work step-by-step:

  1. Begin at the very top of the tree, which is the main starting point, and recognize that its value is allowed to be anything since there are no restrictions yet.
  2. When moving to the left branch, remember that all values down this path must be strictly smaller than the current parent value, while keeping whatever lower limit was inherited from above.
  3. When moving to the right branch, ensure that all values down this path must be strictly greater than the current parent value, while keeping whatever upper limit was inherited from above.
  4. Check every single node you visit to make sure its value fits comfortably inside its currently assigned allowed range.
  5. If any node breaks this rule by falling outside its permitted boundaries, immediately declare that the tree is invalid.
  6. Successfully reach and verify the deepest endpoints of the tree without any violations to confirm that the entire structure is a valid binary search tree.

Code Implementation

class Solution:
    def isValidBST(self, root_node) -> bool:
        def validate_node(current_node, lower_bound, upper_bound):
            if current_node is None:
                return True

            # Node value must respect boundaries to preserve the binary search tree invariant.
            if (lower_bound is not None and current_node.val <= lower_bound) or (upper_bound is not None and current_node.val >= upper_bound):
                return False

            # Moving left restricts the upper limit because all descendants must be smaller.
            if not validate_node(current_node.left, lower_bound, current_node.val):
                return False

            # Moving right restricts the lower limit because all descendants must be larger.
            if not validate_node(current_node.right, current_node.val, upper_bound):
                return False

            return True

        return validate_node(root_node, None, None)

Big(O) Analysis

Time Complexity
O(n) – The time complexity is driven by the recursive traversal of the binary tree, visiting every single node exactly once to check its value against the allowed boundaries. For a tree containing n nodes, we perform a constant amount of comparison and boundary-updating work at each node. This means the total number of operations scales directly with the number of nodes, approximating c * n operations, which simplifies to O(n).
Space Complexity
O(h) – The space complexity is determined by the recursion stack frames required to walk through the tree as described in the steps. In the worst-case scenario, such as a completely unbalanced tree, the depth of the recursion matches the total number of nodes N, leading to linear auxiliary space. For a balanced tree, the maximum depth reaches log(N), meaning the recursion stack grows logarithmically with the input size. Thus, the extra memory used by the traversal algorithm directly scales with the height of the tree.

Edge Cases

Null or empty root node
How to Handle:
Return true immediately because an empty tree is vacuously a valid BST.
Single-node tree
How to Handle:
Return true since a tree with only a root has no children to violate BST properties.
Duplicate values anywhere in the tree
How to Handle:
Enforce strict inequality constraints where left child must be strictly less than and right child strictly greater than the parent.
Node values spanning extreme integer limits like Integer.MIN_VALUE or Integer.MAX_VALUE
How to Handle:
Use 64-bit integer ranges or null pointer bounds to avoid boundary integer collisions.
Subtree values that violate ancestor constraints locally despite valid parent-child relationships
How to Handle:
Propagate dynamic valid minimum and maximum boundaries down the recursive call stack.
Highly skewed binary tree resembling a linked list
How to Handle:
Ensure the recursive approach handles deep stacks or utilize iterative traversals to prevent stack overflow.
Negative numbers and zero values
How to Handle:
Treat negative numbers and zero just like any other integer by relying on relative comparison operators.
Extremely deep tree exceeding standard recursion depth limits
How to Handle:
Convert the recursive validation to an iterative stack-based approach to avoid stack overflow exceptions.
0/257 completed