# 669. Trim a Binary Search Tree

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

## solution

* 小于low，那么所有左子树都小于low可以舍弃，返回右子树
* 大于high，那么所有右子树都大于high可以舍弃，返回左子树
* 对于位于期间的节点，递归其子树，左子树的返回节点接在左子树上，可能是正常节点，也可能是舍弃后返回的节点

```python
class Solution:
    def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
        if not root:
            return None
        if root.val > high:
            return self.trimBST(root.left, low, high)
        if root.val < low:
            return self.trimBST(root.right, low, high)

        if root.val >= low and root.val <= high:
            root.left = self.trimBST(root.left, low, high)
            root.right = self.trimBST(root.right, low, high)
        return root
```

时间复杂度：O()\
空间复杂度：O()

## follow up

[1110. Delete Nodes And Return Forest](https://longxingtan.gitbook.io/mle-interview/01_leetcode/07_dfs/1110.-delete-nodes-and-return-forest)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://longxingtan.gitbook.io/mle-interview/01_leetcode/07_dfs/669.-trim-a-binary-search-tree.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
