一、刷题:
1.leetcode题目 669. 修剪二叉搜索树 - 力扣(LeetCode)
先复习一下二叉树搜索的性质:设x是二叉搜索树中的一个结点。如果y是x左子树中的一个结点,那么y.key≤x.key。如果y是x右子树中的一个结点,那么y.key≥x.key。
解决:
# 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 trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
if root is None:
return None
if root.val<low:
if root.right is None:
return None
if root.right is not None:
return self.trimBST(root.right,low,high)
if root.val>high:
if root.left is None:
return None
if root.left is not None:
return self.trimBST(root.left,low,high)
root.left = self.trimBST(root.left,low,high)
root.right = self.trimBST(root.right,low,high)
return root
2.leetcode题目 108. 将有序数组转换为二叉搜索树 - 力扣(LeetCode):
先复习一下平衡二叉树的定义:
判断「平衡二叉树」的 2 个条件:
①是二叉排序树
②任何一个节点的左子树或者右子树都是平衡二叉树(左右高度差小于等于 1)
解决:
# 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]:
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)
3.leetcode题目
解决:
①递归法:
# 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 convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
pre = 0
def dfs(cur):
nonlocal pre
if cur is None:
return None
cur.right = dfs(cur.right)
cur.val += pre
pre = cur.val
cur.left = dfs(cur.left)
return cur
cur = dfs(root)
return cur
②迭代法:
# 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 convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
pre = 0
stack = []
cur = root
while cur or stack:
if cur:
stack.append(cur)
cur = cur.right
else:
cur = stack.pop()
cur.val += pre
pre = cur.val
cur = cur.left
return root