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


A tree is a binary search tree if it has all the left child lesser than the node elements and all the right child greater than the node elements. Initially we check whether the node has any value, if the node is null then we consider as valid binary search tree and return true. After checking the node null result, we call the recursive method isValidBST by passing the node, min value and max value. If the root value is lesser than min and the root value is greater than max we consider as not a binary search tree and return false else we call isValidBST method recursively by passing the left and right value until it checks all the nodes

Example

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 <= min || root.Value >= max){
         return false;
      }
      return isValidBST(root.LeftChild, min, root.Value) && isValidBST(root.RightChild,
      root.Value, max);
   }
}

Input

   5
  2 6
1  3

Output

True

Updated on: 17-Aug-2021

286 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements