根据已排序数组创建平衡二叉查找树
需要认识到,平衡二叉查找树的中序遍历即为有序数组。
递归解法:
# 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:
return self.createBST(nums, 0, len(nums) - 1)
def createBST(self, nums, left, right):
if left > right:
return None
mid = left + (right-left)//2
print(mid)
# print(nums[mid])
root = TreeNode()
root.val = nums[mid]
root.left = self.createBST(nums, left, mid-1)
root.right = self.createBST(nums, mid+1, right)
return root
网友评论