File size: 2,097 Bytes
c574d3a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 |
class BSS{
static Node root;
static class Node{
int data;
Node left;
Node right;
Node(int d){
data = d;
left = null;
right = null;
}
}
Node RInsert(Node p, int key){
Node t = null;
if(p==null){
t = new Node(key);
return t;
}
if(key <p.data){
p.left = RInsert(p.left,key);
}
else if(key>p.data){
p.right = RInsert(p.right,key);
}
return p;
}
// Height , if pred or succ have more height then take it and replace it with the node to be deleted
int Height(Node n){
int x,y;
if(n==null){
return 0;
}
x = Height(n.left);
y = Height(n.right);
if(x>y)
{
return x+1;
}
else
{
return y+1;
}
}
Node InPre(Node p){
while(p!=null && p.right!=null){
p = p.right;
}
return p;
}
Node InS(Node p){
while(p!=null && p.left!=null){
p=p.left;
}
return p;
}
Node Delete(Node p, int key){
Node q;
// if root is null. retrurn
if(p==null){
return null;
}
if(p.left==null && p.right==null){
if(p==root){
root = null;
}
return null;
}
if(key<p.data){
p.left = Delete(p.left,key);
}
else if(key>p.data){
p.right = Delete(p.right,key);
}
// if both are equal with eachother
else{
if(Height(p.left)>Height(p.right)){
q = InPre(p.left);
p.data = q.data;
p.left = Delete(p.left,q.data);// delete q
}
else{
q = InS(p.right);
p.data = q.data;
p.right = Delete(p.right,q.data);
}
}
return p;
}
void Pre(Node n){
if(n!=null){
System.out.print(n.data+" ");
Pre(n.left);
Pre(n.right);
}
}
public static void main(String[] args){
BSS l = new BSS();
root = l.RInsert(root,32);
l.RInsert(l.root,3);
l.RInsert(l.root,6);
l.RInsert(l.root,5);
l.Pre(l.root);
System.out.println("\n");
l.Delete(l.root,3);
l.Pre(l.root);
}
}
|