Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 21.3k
Expand file tree
/
Copy pathCheckBinaryTreeIsValidBST.java
More file actions
Latest commit
30 lines (26 loc) · 1.05 KB
/
Copy pathCheckBinaryTreeIsValidBST.java
File metadata and controls
30 lines (26 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
packagecom.thealgorithms.datastructures.trees;
/**
* This code recursively validates whether given Binary Search Tree (BST) is balanced or not.
* Trees with only distinct values are supported.
* Key points:
* 1. According to the definition of a BST, each node in a tree must be in range [min, max],
* where 'min' and 'max' values represent the child nodes (left, right).
* 2. The smallest possible node value is Integer.MIN_VALUE, the biggest - Integer.MAX_VALUE.
*/
publicfinalclassCheckBinaryTreeIsValidBST {
privateCheckBinaryTreeIsValidBST() {
}
publicstaticbooleanisBST(BinaryTree.Noderoot) {
returnisBSTUtil(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
privatestaticbooleanisBSTUtil(BinaryTree.Nodenode, intmin, intmax) {
// empty tree is a BST
if (node == null) {
returntrue;
}
if (node.data < min || node.data > max) {
returnfalse;
}
return (isBSTUtil(node.left, min, node.data - 1) && isBSTUtil(node.right, node.data + 1, max));
}
}