LeetCode - Convert Sorted Array to Binary Search Tree

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

Solution:

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public TreeNode buildTree(int[] arr, int left, int right){
12         if(left > right) return null;
13         int mid = (left + right) >> 1;
14         TreeNode r = new TreeNode(arr[mid]);
15         r.left = buildTree(arr, left, mid - 1);
16         r.right = buildTree(arr, mid + 1, right);
17         return r;
18     }
19     public TreeNode sortedArrayToBST(int[] num) {
20         // Start typing your Java solution below
21         // DO NOT write main() function
22         return buildTree(num, 0, num.length-1);
23     }
24 }

 

posted @ 2013-01-29 08:02  cradle  阅读(462)  评论(0编辑  收藏  举报