LeetCode(力扣)669. 修剪二叉搜索树Python

LeetCode669. 修剪二叉搜索树

    • 题目链接
    • 代码

题目链接

https://leetcode.cn/problems/trim-a-binary-search-tree/
LeetCode(力扣)669. 修剪二叉搜索树Python_第1张图片
LeetCode(力扣)669. 修剪二叉搜索树Python_第2张图片

代码

递归

# 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 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

你可能感兴趣的:(leetcode,python,算法)