我写的:
/**
* Definition for a binary tree node.* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode trimBST(TreeNode root, int L, int R) {
if(root==null){
return null;
}
if(root.val<L){
if(root.right==null){
return null;
}
return trimBST(root.right,L,R);
}
if(root.val>R){
if(root.left==null){
return null;
}
return trimBST(root.left,L,R);
}
if(root.val==L){
if(root.right==null){
root.left=null;
return root;
}
TreeNode node=trimBST(root.right,L,R);
root.right=node;
root.left=null;
return root;
}
if(root.val==R){
if(root.left==null){
root.right=null;
return root;
}
TreeNode node=trimBST(root.left,L,R);
root.left=node;
root.right=null;
return root;
}
TreeNode node1=null;
TreeNode node2=null;
if(root.left!=null)
node1=trimBST(root.left,L,R);
if(root.right!=null)
node2=trimBST(root.right,L,R);
root.left=node1;
root.right=node2;
return root;
}
}
不知名大佬写的:
public
TreeNode trimBST(TreeNode root, int L, int R) { if(root
== null)
return
null;
if(root.val
>= L && root.val
<= R) { root.left = trimBST(root.left, L, R); root.right = trimBST(root.right, L, R);
return
root; } if(root.val
< L) return
trimBST(root.right, L, R); if(root.val
> R) return
trimBST(root.left, L, R);}