Refactor BSTFromSortedArray (#4162)

This commit is contained in:
Albina Gimaletdinova
2023-04-22 10:53:12 +03:00
committed by GitHub
parent c01a382d94
commit 4c18e60671
5 changed files with 87 additions and 51 deletions

View File

@ -0,0 +1,33 @@
package com.thealgorithms.datastructures.trees;
import com.thealgorithms.datastructures.trees.BinaryTree.Node;
/**
* Given a sorted array. Create a balanced binary search tree from it.
*
* Steps: 1. Find the middle element of array. This will act as root 2. Use the
* left half recursively to create left subtree 3. Use the right half
* recursively to create right subtree
*/
public class BSTFromSortedArray {
public static Node createBST(int[] array) {
if (array == null || array.length == 0) {
return null;
}
return createBST(array, 0, array.length - 1);
}
private static Node createBST(int[] array, int startIdx, int endIdx) {
// No element left.
if (startIdx > endIdx) {
return null;
}
int mid = startIdx + (endIdx - startIdx) / 2;
// middle element will be the root
Node root = new Node(array[mid]);
root.left = createBST(array, startIdx, mid - 1);
root.right = createBST(array, mid + 1, endIdx);
return root;
}
}

View File

@ -8,7 +8,7 @@ package com.thealgorithms.datastructures.trees;
* 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 class ValidBSTOrNot {
public class CheckBinaryTreeIsValidBST {
public static boolean isBST(BinaryTree.Node root) {
return isBSTUtil(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}

View File

@ -1,44 +0,0 @@
package com.thealgorithms.datastructures.trees;
import com.thealgorithms.datastructures.trees.BinaryTree.Node;
/**
* Given a sorted array. Create a balanced binary search tree from it.
*
* Steps: 1. Find the middle element of array. This will act as root 2. Use the
* left half recursively to create left subtree 3. Use the right half
* recursively to create right subtree
*/
public class CreateBSTFromSortedArray {
public static void main(String[] args) {
test(new int[] {});
test(new int[] { 1, 2, 3 });
test(new int[] { 1, 2, 3, 4, 5 });
test(new int[] { 1, 2, 3, 4, 5, 6, 7 });
}
private static void test(int[] array) {
BinaryTree root = new BinaryTree(createBst(array, 0, array.length - 1));
System.out.println("\n\nPreorder Traversal: ");
root.preOrder(root.getRoot());
System.out.println("\nInorder Traversal: ");
root.inOrder(root.getRoot());
System.out.println("\nPostOrder Traversal: ");
root.postOrder(root.getRoot());
}
private static Node createBst(int[] array, int start, int end) {
// No element left.
if (start > end) {
return null;
}
int mid = start + (end - start) / 2;
// middle element will be the root
Node root = new Node(array[mid]);
root.left = createBst(array, start, mid - 1);
root.right = createBst(array, mid + 1, end);
return root;
}
}