669. 修剪二叉搜索树

https://leetcode-cn.com/problems/trim-a-binary-search-tree/

解法一:

1.若root的val < L,则其左子树必小于L,因此root和其左子树不用再管,处理右子树.

2.若root的val > R,思路类比于2.

3.如果root在[L,R]范围内,返回root,并处理它的左子树和右子树.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def trimBST(self, root: TreeNode, L: int, R: int) -> TreeNode:
        if not root:
            return None
        if root.val < L:
            return self.trimBST(root.right, L, R)
        elif root.val > R:
            return self.trimBST(root.left, L, R)
        else:
            root.left = self.trimBST(root.left, L, R)
            root.right = self.trimBST(root.right, L, R)
            return root

最后更新于