public class Node {
int key;
float data;
Node leftChild;
Node rightChild;
Node parent;
public Node(int k){
key=k;
}
}
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
public class BinaryTree {
Node root=null;
public BinaryTree(){
insert(new Node(7));
insert(new Node(1));
insert(new Node(5));
}
static void inordine(Node x){ // traversarea arborelui in inordine
if (x!=null){
inordine(x.leftChild);
System.out.println(x.key);
inordine(x.rightChild);
}
}
static void preordine(Node x){ // traversarea arborului in preordine
if (x!=null){
System.out.println(x.key);
preordine(x.leftChild);
preordine(x.rightChild);
}
}
static void postordine(Node x){ // traversarea arborului in postordiine
if (x!=null){
postordine(x.leftChild);
postordine(x.leftChild);
System.out.println(x.key);
}
}
static Node cauta_rec(Node x, int k){ // cautarea recursiva
if((x==null)||(k==x.key)){
return x;
}
if(k<x.key){
return cauta_rec(x.leftChild,k);
}
else
return cauta_rec(x.rightChild,k);
}
static Node cautare_ite(Node x,int k){ // cautare iterativa mult mai eficienta !!!! :P
while((x!=null)&&(k!=x.key)){
if (k<x.key)
x=x.leftChild;
else
x=x.rightChild;
}
return x;
}
static Node minim (Node x){ // Minimul :)
while(x.leftChild!=null){
x=x.leftChild;
}
return x;
}
static Node maxim(Node x){ // maximul
while(x.rightChild!=null){
x=x.rightChild;
}
return x;
}
static Node succesor(Node x){ // succesorul
if (x.rightChild!=null)
return minim(x.rightChild);
Node y=x.parent;
while((y!=null)&&(x==y.rightChild)){
x=y;
y=y.parent;
}
return y;
}
Node sterge(Node z){ // stergerea
Node x,y;
if((z.leftChild==null)||(z.rightChild==null))
y=z;
else
y=succesor(z);
if(y.leftChild!=null)
x=y.leftChild;
else
x=y.rightChild;
if(x!=null)
x.parent=y.parent;
if(y.parent==null)
root=x;
else if (y==y.parent.leftChild)
y.parent.leftChild=x;
else
y.parent.rightChild=x;
if(y!=z)
z.key=y.key;
return y;
}
public void insert(Node z){
Node y=null;
Node x=root;
while(x!=null){
y=x;
if(z.key<x.key) x=x.leftChild;
else x=x.rightChild;
}
z.parent=y;
if(y==null)root=z;
else if(z.key<y.key) y.leftChild=z;
else y.rightChild=z;
}
public static void main(String[] args) {
BinaryTree binaryTree1 = new BinaryTree();
BinaryTree.inordine(binaryTree1.root); // traversarea in ordine
Node x=BinaryTree.cautare_ite(binaryTree1.root,7); // cautarea recursiva
System.out.println(x.key);
x=BinaryTree.minim(binaryTree1.root); // minimul
System.out.println(x.key);
x=BinaryTree.maxim(binaryTree1.root); // maximul
System.out.println(x.key);
Node y=new Node(4); // apelul succesorului
binaryTree1.insert(y);
System.out.println(succesor(y));
binaryTree1.sterge(binaryTree1.root); //stergerea
BinaryTree.inordine(binaryTree1.root);
}
}
No comments:
Post a Comment