0% found this document useful (0 votes)
2 views3 pages

Binary HEIGHTdelete

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views3 pages

Binary HEIGHTdelete

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

//

public class Node {


int data;
Node right;
Node left;

public Node(int ele) {


this.data= ele;
left = null;
right= null;
}
}

//

public class binarytree {


Node root;
public binarytree(int ele) {
root = new Node(ele);
root.left = null;
root.right = null;
}
public void insert(int ele) {
if(root==null)return;
Node newnode = new Node(ele);
Node current = root;
while(current!=null) {
while(current!= null && current.data<ele) {
if(current.right==null) {
current.right=newnode;return;
}
current=current.right;
}
while(current!=null&&current.data>ele) {
if(current.left==null) {
current.left=newnode;
return;
}
current=current.left;
}
if(current!=null&&current.data==ele) {
System.err.println("Not allowd");
return;

}
}
}
public int delete(Node parent , Node root,int ele) {
if(root==null)return -1;
int temp=0;
if(root.data>ele) {
parent=root;
delete(parent, root.left, ele);
}else if(root.data<ele) {
parent=root;
delete(parent, root.right, ele);
}else {
if(root.right==null && root.left==null) {
if(parent.left==root)parent.left=null;
else parent.right = null;

}
if(root.left==null) {
if(parent.left==root)parent.left=root.right;
else parent.right=root.right;

}
if(root.right==null) {
if(parent.left==root)parent.left=root.left;
else parent.right=root.left;

}
if(root.left != null&& root.right!= null) {
temp= root.data;
int val = largest(root.left);
root.data=val;
delete(root, root.left, val);

}
return temp;
}
private int largest(Node root) {
if(root.right != null)return largest(root.right);
return root.data;

}
public void inorder(Node root) {
if(root.left!=null)inorder(root.left);
System.out.println(root.data);
if(root.right!=null)inorder(root.right);
}
public void print() {
inorder(root);
}
public void deletefun() {
delete(null, root, 15);

}
}

//

public class tester {


public static void main(String[] args) {
binarytree tree = new binarytree(15);
tree.insert(20);
tree.insert(12);
tree.insert(8);
tree.insert(14);
tree.insert(18);
tree.insert(22);
tree.deletefun();
tree.print();
}
}

You might also like