AVL,在本题中:
1.由于构造的树的AVL,其子树高度差不超过1. 所以在选值时,要选nums中间的值作为node
2.由于每一颗子树都是AVL,所以需要使用递归 每次都选择区间中值构造Node
代码借鉴官方答案:
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
def helper(left,right):
#底部思想:
if left>right :
return None
#顶部思想:
point = (left+right)//2
node = TreeNode(nums[point])
node.left = helper(left,point-1)
node.right = helper(point+1,right)
return node
return helper(0,len(nums)-1)
原文地址:https://www.cnblogs.com/ChevisZhang/p/12642860.html
时间: 2024-10-09 16:15:41