题目描述

给你二叉搜索树的根节点 root ,同时给定最小边界low 和最大边界 high。通过修剪二叉搜索树,使得所有节点的值在[low, high]中。修剪树不应该改变保留在树中的元素的相对结构(即,如果没有被移除,原有的父代子代关系都应当保留)。 可以证明,存在唯一的答案。

所以结果应当返回修剪好的二叉搜索树的新的根节点。注意,根节点可能会根据给定的边界发生改变。

示例链接

解题思路

递归的写法,递归到当前节点root时:

  • root->val 小于 low,则返回右边的子树
  • root->val 大于high,则返回左边的子树
    1. /**
    2. * Definition for a binary tree node.
    3. * struct TreeNode {
    4. * int val;
    5. * TreeNode *left;
    6. * TreeNode *right;
    7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
    8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
    10. * };
    11. */
    12. class Solution {
    13. public:
    14. TreeNode* trimBST(TreeNode* root, int low, int high) {
    15. if (!root)
    16. return NULL;
    17. if (root->val < low)
    18. return trimBST(root->right, low, high);
    19. if (root->val > high)
    20. return trimBST(root->left, low, high);
    21. root->left = trimBST(root->left, low, high);
    22. root->right = trimBST(root->right, low, high);
    23. return root;
    24. }
    25. };