669. 修剪二叉搜索树

image.png
image.png

递归

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode() {}
  8. * TreeNode(int val) { this.val = val; }
  9. * TreeNode(int val, TreeNode left, TreeNode right) {
  10. * this.val = val;
  11. * this.left = left;
  12. * this.right = right;
  13. * }
  14. * }
  15. */
  16. class Solution {
  17. public TreeNode trimBST(TreeNode root, int low, int high) {
  18. if(root == null ) return null;
  19. if(root.val < low ) return trimBST(root.right, low, high );
  20. if(root.val > high ) 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. }