代码:
# 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 not root:
return root
if root.val < low:
return self.trimBST(root.right, low, high)
if root.val >high:
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
108. 将有序数组转换为二叉搜索树
思路:选取中间数作为中节点,当长度为偶数时,取左侧节点也可以,右侧节点也行
代码:
# 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 traversal(nums, left, right):#返回根节点,区间定义是左闭右闭
if left > right:
return None
mid = left + right >> 1
root = TreeNode(nums[mid])
root.left = traversal(nums, left, mid - 1)
root.right = traversal(nums, mid + 1, right)
return root
return traversal(nums, 0, len(nums) - 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 __init__(self):
self.pre = 0
def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
def traversal(cur):
if not cur:
return
traversal(cur.right)
cur.val += self.pre
self.pre = cur.val
traversal(cur.left)
traversal(root)
return root