Q108 Convert Sorted Array to Binary Search Tree

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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容