* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode searchNode(TreeNode node, int key){
if(node.left == null && node.right == null) return null;
else{
int leftval = -1;
int rightval = -1;
if(node.left != null) leftval = node.left.val;
if(node.right != null) rightval = node.right.val;
if(key == leftval || key == rightval) return node;
else{
if(key < node.val) return searchNode(node.left, key);
else return searchNode(node.right, key);
}
}
}
public TreeNode deleteNode(TreeNode root, int key) {
if(root == null) return root;
TreeNode node = root;
TreeNode parent = null;
Boolean left = true;
if(root.val != key){
parent = searchNode(root, key);
if(parent == null) return root;
if(parent.left != null) if(parent.left.val == key) node = parent.left;
if(parent.right != null) {
if(parent.right.val == key){
node = parent.right;
left = false;
}
}
}
if(node.left == null && node.right == null){
if(parent == null) return null;
if(left) parent.left = null;
else parent.right = null;
}
else if(node.right != null && node.left == null){
if(parent == null) return node.right;
else{
if(left) parent.left = node.right;
else parent.right = node.right;
}
}
else if(node.right == null && node.left != null){
if(parent == null) return node.left;
else{
if(left) parent.left = node.left;
else parent.right = node.left;
}
}
else{
if(node.right != null){
TreeNode leftmost = node.right;
TreeNode leftmost_parent = node;
while(leftmost.left != null){
leftmost_parent = leftmost;
leftmost = leftmost.left;
}
node.val = leftmost.val;
if(leftmost_parent == node) node.right = node.right.right;
else leftmost_parent.left = leftmost.right;
}
else{
node.right = null;
}
}
return root;
}
}