Leetcode–Convert Sorted Array to Binary Search Tree

The Problem:

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

Notes:

  1. BST is left node left less than parent then less than right. As the input array is in ascending order, in each recursion , take the middle element as parent,  first half start a branch to construct left child, latter half start another branch to construct right child.

Java Solution

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode sortedArrayToBST(int[] num) {
        int len = num.length;
        if(len==0) return null;
        return constructTree(num, 0, len-1);
        
    }
    
    private TreeNode constructTree(int[] num, int start, int end){
        if(start > end) return null;
        int mid = (start+end)/2;
        TreeNode parent = new TreeNode(num[mid]);
        parent.left = constructTree(num, start, mid-1);
        parent.right = constructTree(num, mid+1, end);
        return parent;
    }
}
Advertisements

One thought on “Leetcode–Convert Sorted Array to Binary Search Tree

  1. Pingback: Leetcode–Convert Sorted List to Binary Search Tree | Linchi is coding

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s