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
2.解法
二叉搜索树如果按中序遍历,得到的是一个有序数组。那么反过来易知,根节点应该是有序数组的中间点,从中间点分开为左右两个有序数组,在分别找出其中间点作为原中间点的左右两个子节点,本质上是二分查找的思想。
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)