class Solution {
public TreeNode searchBST(TreeNode root, int val) {
if (root == null) {
return null;
}
if (val < root.val) {
return searchBST(root.left, val);
}
else if (val > root.val) {
return searchBST(root.right, val);
}
else {
return root;
}
}
}
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) {
return new TreeNode(val, null, null);
}
if (val < root.val) {
root.left = insertIntoBST(root.left, val);
}
else if (val > root.val) {
root.right = insertIntoBST(root.right, val);
}
return root;
}
}
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) {
return null;
}
if (key < root.val) {
root.left = deleteNode(root.left, key);
}
else if (key > root.val) {
root.right = deleteNode(root.right, key);
}
else {
if (root.left == null) {
return root.right;
}
if (root.right == null) {
return root.left;
}
TreeNode max = findMax(root.left);
max.left = deleteMax(root.left);
max.right = root.right;
root = max;
}
return root;
}
public TreeNode deleteMax(TreeNode root) {
if (root.right == null) {
return root.left;
}
root.right = deleteMax(root.right);
return root;
}
public TreeNode findMax(TreeNode root) {
while (root.right != null) {
root = root.right;
}
return root;
}
}