《LeetCode力扣练习》代码随想录——二叉树(修剪二叉搜索树—Java)
刷题思路来源于 代码随想录
669. 修剪二叉搜索树
-
二叉树-递归
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public TreeNode trimBST(TreeNode root, int low, int high) { return recursion(root, low, high); } private TreeNode recursion(TreeNode root, int low, int high) { if (root == null) { return null; } if (root.val < low) { return recursion(root.right, low, high); } if (root.val > high) { return recursion(root.left, low, high); } root.left = recursion(root.left, low, high); root.right = recursion(root.right, low, high); return root; } }