
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check Validity of 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
Advertisements