修剪二叉搜索树
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
if(root == null)return root;
TreeNode newRoot = root;
if(root.val <low){
return trimBST(root.right , low , high);
}
if(root.val > high){
return trimBST(root.left , low , high);
}
root.left = trimBST(root.left ,low ,high);
root.right = trimBST(root.right,low , high);
return root;
}
}
删除二叉搜索树中的节点
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if(root == null)return root;
if(root.val == key){
if(root.left == null){
return root.right;
}else if(root.right == null){
return root.left;
}else{
TreeNode cur = root.right;
while(cur.left != null){
cur = cur.left;
}
cur.left = root.left;
root = root.right;
return root;
}
}
if (root.val > key) root.left = deleteNode(root.left, key);
if (root.val < key) root.right = deleteNode(root.right, key);
return root;
}
}
二叉搜索树中的插入操作
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null)return new TreeNode(val);
TreeNode newRoot = root;
TreeNode pre = root;
while(root != null){
pre = root;
if(root.val > val){
root = root.left;
}else if(root.val < val){
root = root.right;
}
}
if(pre.val > val){
pre.left = new TreeNode(val);
}else if(pre.val <val){
pre.right = new TreeNode(val);
}
return newRoot;
}
}