Problem Statement: You have been given root
of a binary tree. Your task is to find whether the given binary tree is valid binary search tree or not.
A binary tree is considered valid if it satisifes below conditions:
- 1. Left subtree of a node contains only nodes with values less than the node's value.
- 2. Right subtree of a node contains only nodes with values greater than the node's value.
- 3. Both the left and right subtrees must be binary search trees.
Example:
Output: true
Approach 1:
Simple inorder traversal and storing the nodes value in ArrayList and lastly checking whether the ArrayList is in sorted order or not. If the ArrayList is in sorted order and doesn't contain any duplicates it means the given tree is a valid binary search tree otherwise not.
Complexity Analysis:
Time Complexity: O(n) for Traversing the nodes of tree + O(n) traversing the list. O(2n).
Space Complexity: O(n) for storing the nodes values.
Approach 2:
Maintain a pointer prev and keep comparing the current node value with prev. If at any stage prev node value becomes greater than or equal to current node value then it is not valid Binary Search Tree.
Code Implementation:
Output:
true
Complexity Analysis:
Time Complexity: O(n), where n is the number of nodes in tree.
Space Complexity: Considering the stack space, if the tree is balanced then O(log n) and if tree is unbalanced then O(n).