forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCheckBinaryTreeIsValidBST.java
More file actions
30 lines (26 loc) · 1.05 KB
/
CheckBinaryTreeIsValidBST.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
package com.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.
*/
public final class CheckBinaryTreeIsValidBST {
private CheckBinaryTreeIsValidBST() {
}
public static boolean isBST(BinaryTree.Node root) {
return isBSTUtil(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
private static boolean isBSTUtil(BinaryTree.Node node, int min, int max) {
// empty tree is a BST
if (node == null) {
return true;
}
if (node.data < min || node.data > max) {
return false;
}
return (isBSTUtil(node.left, min, node.data - 1) && isBSTUtil(node.right, node.data + 1, max));
}
}