Many times we need to validate a Binary Search tree i.e. verifying its properties,

  • Left subtree of each node contains the nodes with value less than the node’s value.
  • Right subtree of each node contains the nodes with value greater than the node’s value.
  • Moreover, left and right subtree of each node must be a Binary Search Tree

For more details on BST check : http://en.wikipedia.org/wiki/Binary_search_tree

bst
Binary Search Tree

Simple and effective solution :

Just iterate with In-Order Traversal and check all elements are in increasing order or not.

Implementation Detail:

Only Variable is required to keep track of the last maximum value. During in-order traversal while visiting each node just check its value is greater than last maximum value or not.
If its value is greater than last maximum value then its fine, otherwise change the internal state to false.


Another Point:

What should be the initial value of max ?

If tree node can contain negative values then use bool bStart variable to keep track of the first element in the list.
Once first element is traversed then only start checking the max value.
There is no need to check the max comparison for first node i.e. Left most node of the tree.

BST Validator class :

Usage Detail,

Node Structure: