方法:后序遍历
    搜索二叉树定义:左子树小于头节点,头节点小于右节点(在做题目时忘记了该定义)

    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==NULL){
    16. return root;
    17. }
    18. if(root!=NULL){
    19. root->left=trimBST(root->left,low,high);
    20. root->right=trimBST(root->right,low,high);
    21. if(root->val>high){
    22. root=root->left;
    23. }
    24. else if(root->val<low){
    25. root=root->right;
    26. }
    27. }
    28. return root;
    29. }
    30. };