# 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. 将有序数组转换为二叉搜索树 - 力扣(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 buildTree(self,nums,lf,rg):
if rg<lf:
return None
mid=(lf+rg)//2
nw=TreeNode(val=nums[mid])
nw.left=self.buildTree(nums,lf,mid-1)
nw.right=self.buildTree(nums,mid+1,rg)
return nw
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
return self.buildTree(nums,0,len(nums)-1)
538. 把二叉搜索树转换为累加树 - 力扣(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 getSum(self,node):
if not node:
return None
self.getSum(node.right)
node.val+=self.pre
self.pre=node.val
self.getSum(node.left)
def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
self.pre=0
self.getSum(root)
return root