題目:
Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.
A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.
給定一個sorted list,將它轉變成高度平衡二元樹(height-balanced binary tree)
高度平衡二元樹定義:所有兩子樹高度最多相差1的binary tree
ex:input:[-10,-3,0,5,9]=>output: [0,-3,9,-10,null,5]or[0,-10,5,null,-3,null,9]
按照題目給的範例,可以看出規律是取mid當root,分開的兩串陣列再取mid當左右節點,以此類推
我們按照這樣的理念實作程式
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
if len(nums)==0: #當沒東西時回傳None,不開新節點
return None
if len(nums)==1: #當值只有一個時,就開此值的節點就好
return TreeNode(nums[0])
mid=len(nums)//2
root=TreeNode(nums[mid])
root.right=self.sortedArrayToBST(nums[mid+1:len(nums)])
root.left=self.sortedArrayToBST(nums[0:mid])
return root
先開一個值為nums[mid]的節點
mid兩邊的list用一樣的手法遞迴不斷往下開左右節點,直到list被切割到長度只剩0或1為止
最後執行時間63ms(faster than 93.48%)
那我們下題見