Leetcode刷题——将有序数组转换为二叉搜索树、平衡二叉树、二叉树的最小深度
1,将有序数组转换为二叉搜索树
给你一个整数数组 nums ,其中元素已经按 升序 排列,请你将其转换为一棵 高度平衡 二叉搜索树。
高度平衡 二叉树是一棵满足「每个节点的左右两个子树的高度差的绝对值不超过 1 」的二叉树。
示例 1:
输入:nums = [-10,-3,0,5,9]
输出:[0,-3,9,-10,null,5]
解释:[0,-10,5,null,-3,null,9] 也将被视为正确答案:
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/convert-sorted-array-to-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
def helper(left,right):
if left>right:
return None
mid=(left+right)//2
root = TreeNode(nums[mid])
root.left = helper(left, mid - 1)
root.right = helper(mid + 1, right)
return root
return helper(0,len(nums)-1)
2,平衡二叉树
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
if not root:
return True
def height(root: Optional[TreeNode]):
if not root:
return 0
return max(height(root.left),height((root.right)))+1
return abs(height(root.left)-height((root.right)))<=1 and self.isBalanced(root.left) and self.isBalanced(root.right)
3,二叉树的最小深度
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
if (not root.left and not root.right):
return 1
depth=1e6
if root.left:
depth=min(self.minDepth(root.left),depth)
if root.right:
depth=min(self.minDepth(root.right),depth)
return depth+1