https://leetcode.cn/problems/trim-a-binary-search-tree/description/
我代码:没利用到树的性质,遍历了每一个节点
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
//遍历所有节点,寻找需要删除的节点
if(root==null) return null;
//遍历
//寻找左右子树中,要删除的节点
if(root!=null)
root.left=trimBST(root.left,low,high);
if(root!=null)
root.right=trimBST(root.right,low,high);
if(root!=null){//如果当前节点需要被删除
if(root.val<low||root.val>high){
root=delete(root);//删除后的根节点
}
}
return root;
}
//删除节点,并保持树结构
public TreeNode delete(TreeNode root){
if(root==null) return null;
if(root.left==null&&root.right==null){
return null;//叶子结点直接删除
}
if(root.left!=null&&root.right==null){
root=root.left;//用左孩子替代
return root;
}
else if(root.left==null&&root.right!=null){
root=root.right;//用右孩子替代
return root;
}
else{//左右孩子都不为空
//把左孩子,放到右子树的最左节点,作为它的左孩子
TreeNode right_left=find(root.right);
right_left=root.left;
root.left=null;
root=root.right;
return root;
}
}
public TreeNode find(TreeNode node){
while(node.left!=null){
node=node.left;
}
return node;
}
}
参考代码:我进行了注释
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
if (root == null) {
return null;
}
if (root.val < low) {
//如果根节点小于左边界,那么根节点和左子树都小于左边界。只需要考虑右子树。
return trimBST(root.right, low, high);
}
//如果根节点大于右边界,那么根节点和右子树都大于右边界。只需要考虑左子树。
if (root.val > high) {
return trimBST(root.left, low, high);
}
// root在[low,high]范围内,那么需要分别寻找左右子树是否要删除
root.left = trimBST(root.left, low, high);
root.right = trimBST(root.right, low, high);
return root;
}
}
还有一种迭代法,没有写出来。