One Leetcode per day-669. Trim the binary search tree [recursion]

Insert picture description here

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def trimBST(self, root, low, high):
        """
        :type root: TreeNode
        :type low: int
        :type high: int
        :rtype: TreeNode
        """
        if root == None: return None;
        # 如果根节点大于high,则返回左子树
        if root.val > high: 
            return self.trimBST(root.left,low,high)
        # 如果根节点小于low,则返回右子树
        if root.val < low:
            return self.trimBST(root.right,low,high)
        # 如果根节点在low和high之间,修剪
        root.left = self.trimBST(root.left,low,high)
        root.right = self.trimBST(root.right,low,high)
        return root

Guess you like

Origin blog.csdn.net/weixin_41041275/article/details/112762401