

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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
- Related Questions & Answers
- C++ Program to Check Whether a Given Tree is Binary Search Tree
- How to invert a binary search tree using recursion in C#?
- C++ Program to Check Whether a given Binary Tree is a Full Binary Tree or not
- Binary Tree to Binary Search Tree Conversion in C++
- Binary Tree to Binary Search Tree Conversion using STL set C++?
- C++ Program to Check Whether an Input Binary Tree is the Sub Tree of the Binary Tree
- Python Program for Depth First Binary Tree Search using Recursion
- Check if a binary tree is subtree of another binary tree in C++
- Optimal Binary Search Tree
- Python Program to Sort using a Binary Search Tree
- Balance a Binary Search Tree in c++
- Implementing a Binary Search Tree in JavaScript
- Binary Search Tree in Javascript
- Binary Search Tree to Greater Sum Tree in C++
- Program to check whether a binary tree is complete or not in Python
Advertisements