Solution: Validate Binary Search Tree
Let's solve the Validate Binary Search Tree problem using the Tree Depth-First Search pattern.
We'll cover the following
Statement#
Given the root of a binary tree, check whether it is a valid binary search tree (BST).
A binary tree is a valid BST if for every node:
-
The value of the node is greater than or equal to the value of its left node.
-
The value of the node is less than or equal to the value of its right node.
-
Both the left and right subtrees are valid BSTs.
Constraints:
-
Node.data -
The tree contains nodes in the range .
Solution#
For this solution, we will recursively
perform the inorder (left subtree, root, right subtree) traversal on the binary tree. We will be using inorder traversal to get elements in sorted order. We will also use a prev variable to hold the value of the previous node visited during the inorder traversal.
We initialize the prev variable with negative infinity. Then, we perform the inorder traversal on the tree and check whether the current node’s value is less than the prev value. If it is, return FALSE since it is not a valid BST. If not, update the value of prev with the current node’s value, and continue the traversal. If all nodes have been traversed and no node’s value was less than the prev value, it means that the tree is a valid BST. Therefore, we return TRUE.
Let’s look at an example below:
1 of 19
2 of 19
3 of 19
4 of 19
5 of 19
6 of 19
7 of 19
8 of 19
9 of 19
10 of 19
11 of 19
12 of 19
13 of 19
14 of 19
15 of 19
16 of 19
17 of 19
18 of 19
19 of 19
Let’s implement the algorithm as discussed above:
Validate Binary Search Tree
Tree Breadth-first Search: Introduction