LeetCode – Convert Sorted Array to Binary Search Tree (Java)

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;
	}
}
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>

  1. Santosh Kumar on 2015-9-5

    https://www.youtube.com/watch?v=VCTP81Ij-EM Here is video for converting sorted array to balanced BST.

  2. Rahul Shukla on 2015-10-13

    https://www.youtube.com/watch?v=VCTP81Ij-EM Here is video for converting sorted array to balanced BST.

  3. Amit Agrawal on 2017-6-1

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

    }

Leave a comment

*