Given a Binary Tree, we have to validate whether it is a valid Binary Search Tree(BST) or not. Print true, if given Binary Tree is a valid BST else print false.

Let’s understand this problem better with an example

15/ \8 25/ \ / \4 12 20 30It's is valid Binary Serach Tree15/ \8 25/ \ / \4 19 20 30It's not a valid BST, becacuse node 19 is voilating the property of BST

#### Algorithm

We know that the Inorder traversal of a Binary Search Tree(BST) is a sorted order of elements present in the tree. Hence we can do the inorder traversal of the above tree and store it in an array. Later we can check if the generated array is sorted or not.

This approach will run in O(N) time, but the space complexity of the above approach is also O(N), because of the additional array.

###### Space optimized approach

In the above approach, the generated array is actually unnecessary except for comparing if the current element is greater than the previous element.

Hence instead of storing all the elements in an array, we will keep track of previous element data value and check if the value of the current node is greater than the previous element or not.

If the current node value is greater than the previous element for all the elements, then it’s a valid BST, else it is not a valid BST.

```
valid_bst(tree, prev)
{
if(tree == NULL)
return true;
if(!valid_bst(tree->left, prev))
return false;
```*//if current element is less than previous node*
* // in inorder traversal than it is not a valid BST*
if(tree->data < prev)
return false;
prev = tree->data;
if(!valid_bst(tree->right, prev))
return false;
return true;
}

#### Implementation of the above algorithm in CPP

###### Output

Input: 15 / \ 8 25 / \ / \ 4 12 20 30 Output:true

#### Time Complexity

The time complexity of the above algorithm is O(N), where N is the number of nodes a given tree because we are going to traverse all the elements of a given tree to check if the tree is valid Binary Search Tree. The space complexity of the above algorithm is O(1) as we are strong only a previous node value in an integer variable.