题目描述
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
题目只有一句话:把一个按升序排列的数组,装换成一个平衡二叉树。
思路
要满足一下条件,对于没有排序的数组来说,就比较麻烦,但对于已排序的数组,大都用二分递归转换方法来处理。
算法逻辑很简单,就是先找到中间元素,创建根节点,左右子树分别用中间元素左边(即小于中间节点的元素)和中间元素右边(即大于中间节点的元素)递归创建。
这样,节点的左子树永远比节点小,右子树永远比节点大,且由于平均递归创建每一层的子树,所以两个子树的高度差不会超过1。
Java代码
//Definition for a binary tree node
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
//将已排序数组变成平衡二叉树
public TreeNode sortedArrayToBST(int[] nums) {
TreeNode node = creatTreeNode(nums,0,nums.length-1);
return node;
}
//递归创建子树,大小为剩余元素中间节点
public TreeNode creatTreeNode(int[] nums,int left,int right) {
if(left>right) {
return null;
}
int mid = (left+right)/2;
TreeNode node = new TreeNode(nums[mid]);
node.left = creatTreeNode(nums, left, mid - 1);
node.right = creatTreeNode(nums, mid+1, right);
return node;
}
Python3代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sortedArrayToBST(self, nums):
""" :type nums: List[int] :rtype: TreeNode """
return self.createBST(nums,0,len(nums)-1)
def createBST(self,nums,low,high):
if low > high:
return None
mid = (low+high)//2
root = TreeNode(nums[mid])
root.left = self.createBST(nums,low,mid-1)
root.right = self.createBST(nums,mid+1,high)
return root