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 every node 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
解題思路:
首先明白平衡二叉樹的定義,注意要是每個結(jié)點必須滿足。因為是將一個有序數(shù)組轉(zhuǎn)化為一個平衡二叉樹,因此,答案可能不唯一。
遞歸,將中間元素作為根節(jié)點,然后將數(shù)組分為左右兩部分。左邊數(shù)組用于遞歸創(chuàng)建左子樹,右邊數(shù)組用于遞歸創(chuàng)建右子樹,直到數(shù)組為空。
Python實現(xiàn):
# 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, num):
if not num: # 如果數(shù)組為空
return None
mid = len(num) // 2
root = TreeNode(num[mid])
root.left = self.sortedArrayToBST(num[:mid]) # 遞歸構(gòu)建左子樹
root.right = self.sortedArrayToBST(num[mid+1:]) # 遞歸構(gòu)建右子樹
return root