Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Java Solution
A typical DFS problem using recursion.
// Definition for binary tree class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public class Solution { public TreeNode sortedArrayToBST(int[] num) { if (num.length == 0) return null; return sortedArrayToBST(num, 0, num.length - 1); } public TreeNode sortedArrayToBST(int[] num, int start, int end) { if (start > end) return null; int mid = (start + end) / 2; TreeNode root = new TreeNode(num[mid]); root.left = sortedArrayToBST(num, start, mid - 1); root.right = sortedArrayToBST(num, mid + 1, end); return root; } } |
other solution would be :
as we know number of elements , we can re-create tree
than, just do in-order traverse, and assign values from array 1..N
public class Node {
int data;
Node left;
Node right;
public Node(final int data) {
this.data = data;
}
public void printTree() {
final Queue list = new LinkedList();
list.add(this);
while (!list.isEmpty()) {
final Node t = list.remove();
System.out.println(t.data);
if (t.left != null) {
list.add(t.left);
}
if (t.right != null) {
list.add(t.right);
}
}
}
}
public class CreateTreeFromArray {
public static void main(final String[] args) {
final CreateTreeFromArray p = new CreateTreeFromArray();
final int[] num = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
final Node root = p.createTree(num, 0, num.length – 1);
root.printTree();
}
// returns the root node
public Node createTree(final int[] num, final int start, final int end) {
if (start > end) {
return null;
}
if (start == end) {
return new Node(num[start]);
}
final int mid = (start + end) / 2;
final Node root = new Node(num[mid]);
root.left = this.createTree(num, start, mid – 1);
root.right = this.createTree(num, mid + 1, end);
return root;
}
}
https://www.youtube.com/watch?v=VCTP81Ij-EM Here is video for converting sorted array to balanced BST.
https://www.youtube.com/watch?v=VCTP81Ij-EM Here is video for converting sorted array to balanced BST.