递归,每次取有序数组中间的数创建当前节点,同时有序数组前半用于构建当前节点的左子树,后半用于构建当前节点的右子树
# 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]) -> TreeNode: root = TreeNode() self.sortedArrayToBSTHelper(root,nums) return root def sortedArrayToBSTHelper(self,root:TreeNode,nums:List[int]): L = len(nums) root.val = nums[L//2] if(L>2): root.left = TreeNode() root.right = TreeNode() self.sortedArrayToBSTHelper(root.left,nums[:L//2]) #构建左子树 self.sortedArrayToBSTHelper(root.right,nums[L//2+1:]) #构建右子树 elif(L==2): root.left= TreeNode(val=nums[0]) else: return
递归yyds,希望这次学了构建搜索树别再忘了…