Skip to content

Fixes: #2706: Create a balanced binary search tree from a sorted array. #2711

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 26, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Fixes: #2706: Create a balanced binary search tree from a sorted array.
  • Loading branch information
akumar-indeed committed Oct 23, 2021
commit ed034ffb16a23a16d886454091178c58623f9910
7 changes: 6 additions & 1 deletion DataStructures/Trees/BinaryTree.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public class BinaryTree {
*
* @author Unknown
*/
class Node {
static class Node {
/** Data for the node */
public int data;
/** The Node to the left of this one */
Expand Down Expand Up @@ -50,6 +50,11 @@ public BinaryTree() {
root = null;
}

/** Parameterized Constructor */
public BinaryTree(Node root) {
this.root = root;
}

/**
* Method to find a Node with a certain value
*
Expand Down
45 changes: 45 additions & 0 deletions DataStructures/Trees/CreateBSTFromSortedArray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package DataStructures.Trees;

import 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;
}
}