How to check whether a binary tree is a valid binary search tree using recursion in C#?

A Binary Search Tree (BST) is a tree structure where each node's left child contains values smaller than the node, and the right child contains values greater than the node. To validate whether a binary tree is a valid BST using recursion, we need to check that each node's value falls within its allowed range based on its position in the tree.

The recursive approach uses upper and lower bounds that get updated as we traverse the tree. For each node, we verify that its value lies within the current bounds, then recursively check the left subtree with updated maximum bound and the right subtree with updated minimum bound.

Valid Binary Search Tree Structure 5 (-?, +?) 2 (-?, 5) 6 (5, +?) 1 (-?, 2) 3 (2, 5) Each node stays within its valid range bounds

Syntax

Following is the syntax for the recursive BST validation method −

public bool isValidBST(Node root) {
    return isValidBST(root, int.MinValue, int.MaxValue);
}

private bool isValidBST(Node root, int min, int max) {
    // Base case and validation logic
}

How It Works

The algorithm works by maintaining valid ranges for each node:

  • Start with the root node having bounds from int.MinValue to int.MaxValue.

  • For each left child, update the maximum bound to the parent's value.

  • For each right child, update the minimum bound to the parent's value.

  • If any node violates its bounds, the tree is not a valid BST.

Example

Here's a complete implementation that validates a binary search tree using recursion −

using System;

public class TreesPgm {
    public class Node {
        public int Value;
        public Node LeftChild;
        public Node RightChild;
        
        public Node(int value) {
            this.Value = value;
        }
        
        public override String ToString() {
            return "Node=" + Value;
        }
    }
    
    public bool isValidBST(Node root) {
        if (root == null) {
            return true;
        }
        return isValidBST(root, int.MinValue, int.MaxValue);
    }
    
    private bool isValidBST(Node root, int min, int max) {
        if (root == null) {
            return true;
        }
        
        if (root.Value = max) {
            return false;
        }
        
        return isValidBST(root.LeftChild, min, root.Value) && 
               isValidBST(root.RightChild, root.Value, max);
    }
    
    public static void Main() {
        TreesPgm tree = new TreesPgm();
        
        // Create the tree:     5
        //                    /   \
        //                   2     6
        //                  / \
        //                 1   3
        
        Node root = new Node(5);
        root.LeftChild = new Node(2);
        root.RightChild = new Node(6);
        root.LeftChild.LeftChild = new Node(1);
        root.LeftChild.RightChild = new Node(3);
        
        bool isValid = tree.isValidBST(root);
        Console.WriteLine("Is valid BST: " + isValid);
        
        // Test with invalid BST
        Node invalidRoot = new Node(5);
        invalidRoot.LeftChild = new Node(2);
        invalidRoot.RightChild = new Node(6);
        invalidRoot.LeftChild.LeftChild = new Node(1);
        invalidRoot.LeftChild.RightChild = new Node(7); // Invalid: 7 > 5
        
        bool isInvalid = tree.isValidBST(invalidRoot);
        Console.WriteLine("Invalid tree result: " + isInvalid);
    }
}

The output of the above code is −

Is valid BST: True
Invalid tree result: False

Edge Cases

The algorithm handles several important edge cases:

  • Empty tree − An empty tree (null root) is considered a valid BST.

  • Single node − A tree with only one node is always a valid BST.

  • Duplicate values − The strict inequality checks (<= and >=) ensure duplicates are not allowed.

Example with Edge Cases

using System;

public class BSTValidator {
    public class Node {
        public int Value;
        public Node LeftChild;
        public Node RightChild;
        
        public Node(int value) {
            this.Value = value;
        }
    }
    
    public bool isValidBST(Node root) {
        return isValidBST(root, int.MinValue, int.MaxValue);
    }
    
    private bool isValidBST(Node root, int min, int max) {
        if (root == null) {
            return true;
        }
        
        if (root.Value = max) {
            return false;
        }
        
        return isValidBST(root.LeftChild, min, root.Value) && 
               isValidBST(root.RightChild, root.Value, max);
    }
    
    public static void Main() {
        BSTValidator validator = new BSTValidator();
        
        // Test empty tree
        Console.WriteLine("Empty tree: " + validator.isValidBST(null));
        
        // Test single node
        Node singleNode = new Node(10);
        Console.WriteLine("Single node: " + validator.isValidBST(singleNode));
        
        // Test duplicate values
        Node duplicateRoot = new Node(5);
        duplicateRoot.LeftChild = new Node(5); // Duplicate value
        Console.WriteLine("Duplicate values: " + validator.isValidBST(duplicateRoot));
    }
}

The output of the above code is −

Empty tree: True
Single node: True
Duplicate values: False

Conclusion

Validating a binary search tree using recursion involves checking that each node's value falls within its valid range based on ancestor values. The recursive approach efficiently traverses the tree while maintaining bounds, ensuring the BST property is satisfied throughout the entire structure.

Updated on: 2026-03-17T07:04:36+05:30

503 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements