# Convert Sorted Array to Binary Search Tree(将有序数组转为二叉搜索树)

## 1.问题描述

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

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of everynode never differ by more than 1.

Example:

Given the sorted array: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

   0
/ \
-3   9
/   /
-10  5


## 3.java版本

import java.util.*;

/**
* Created by wanglei on 19/4/14.
*/
public class ArrayToBST {

public static TreeNode buildTree(int[] nums) {
TreeNode root = null;
if (nums.length > 0) {
int midPos = nums.length / 2;
int mid = nums[midPos];
root = new TreeNode(mid);
root.left = buildTree(Arrays.copyOfRange(nums, 0, midPos));
root.right = buildTree(Arrays.copyOfRange(nums, midPos+1, nums.length));
}

return root;
}

public static void preTraverse(TreeNode root) {
if (root != null) {
preTraverse(root.left);
System.out.println(root.data);
preTraverse(root.right);
}
}

public static void main(String[] args) {
int[] nums = {-10, -3, 0, 5, 9};
TreeNode root = buildTree(nums);
preTraverse(root);
}
}


## 4.python版本

class TreeNode(object):

def __init__(self, val):
self.val = val
self.left = None
self.right = None

def sortedArrayToBST(nums):
if nums:
midPos = len(nums) / 2
mid = nums[midPos]
root = TreeNode(mid)
root.left = sortedArrayToBST(nums[:midPos])
root.right = sortedArrayToBST(nums[midPos+1:])
return root

def printTree(root):
if root:
printTree(root.left)
print root.val
printTree(root.right)

nums = [-10, -3, 0, 5, 9]
root = sortedArrayToBST(nums)
printTree(root)