public class Node {
int value;
Node left;
Node right;
public Node(int value) {
this.value = value;
}
public void add(Node node) {
if (node==null){
return;
}
if (this.value>node.value){
if (this.left==null){
this.left =node;
}else {
this.left.add(node);
}
}else {
if (this.right==null){
this.right =node;
}else {
this.right.add(node);
}
}
}
public void midPrint(Node root) {
if (root == null){
return;
}
midPrint(root.left);
System.out.println(root.value);
midPrint(root.right);
}
public Node searchNode(Node node) {
if (this.value == node.value){
return this;
}else if (this.value>node.value){
if (this.left == null) return null;
return left.searchNode(node);
}else {
if (this.right == null) return null;
return right.searchNode(node);
}
}
public void deleteNode(Node node) {
}
public Node searchParent(Node node) {
if ((this.left.value==node.value && this.left !=null)||(this.right.value==node.value&& this.right !=null)){
return this;
}else{
if (this.left!=null && this.value>node.value){
return this.left.searchParent(node);
}else if (this.right!=null && this.value<node.value){
return this.right.searchParent(node);
}
return null;
}
}
}
public class BinarySortTree {
Node root;
public void add(Node node){
if (root == null ){
root=node;
}else{
root.add(node);
}
}
public void midPrint() {
if (root !=null){
root.midPrint(root);
}
}
public Node searchNode(Node node){
if (root==null){
return null ;
}else {
return root.searchNode(node);
}
}
public void deleteNode(Node node){
if (root == null){
return;
}else {
Node target = searchNode(node);
if (target==null){
return;
}
Node parent = searchParent(node);
if (target.left==null && target.right==null){
if (target==parent.left){
parent.left=null;
}else {
parent.right=null;
}
}else if (target.left!=null && target.right!=null){
Node minNode = findMinNode(target.right);
target.value=minNode.value;
}else {
if (target.left!=null){
if (target==parent.left){
parent.left=target.left;
}else {
parent.right=target.left;
}
}else {
if (target==parent.left){
parent.left=target.right;
}else {
parent.right=target.right;
}
}
}
}
}
private Node findMinNode(Node node) {
Node target = node;
while (target.left!=null){
target = target.left;
}
deleteNode(target);
return target;
}
public Node searchParent(Node node){
if (root == null){
return null;
}else{
return root.searchParent(node);
}
}
}
public static void main(String[] args) {
BinarySortTree binarySortTree = new BinarySortTree();
int[] arr = new int[]{7,3,10,12,5,1,9};
for (int i:arr){
binarySortTree.add(new Node(i));
}
binarySortTree.midPrint();
System.out.println("--------------------");
binarySortTree.deleteNode(new Node(3));
binarySortTree.midPrint();
}