常见算法的进阶打怪路程|二叉树 08

. - 力扣(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 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值