SlideShare a Scribd company logo
1 of 15
Download to read offline
Here is the code given in the instructions:
class AVL {
Node root;
private class Node {
int data;
Node left, right;
int height;
private Node(int D, Node L, Node R, int H) {
data=D;
left=L;
right=R;
height=H; // user has to set height
} // of constructor Node
} //of Node
static private void UpdateHeight(Node T) {
if (T ==null) return;
else T.height = Math.max(HEIGHT(T.left),HEIGHT(T.right)) + 1;
} // UPdate Height
static private int HEIGHT(Node T) {
if (T== null ) return(-1);
else return (T.height);
}
// we need to more our right child up
static private Node LeftRotate(Node T) {
System.out.println("left rotate with data " + T.data);
Node Tr;
Tr=T.right; // right child
T.right=Tr.left; // our right child IS NOW hhh
Tr.left=T; // move T down to the left
UpdateHeight(Tr.left); // update the height of T
UpdateHeight(Tr); // update hte height of the new root
return Tr;
} // of LeftRotate
// we move our immediate left node up.
// in doing so, we are now immediat right of our left child
static private Node RightRotate(Node T) {
Node Tl;
System.out.println("left rotate with data " + T.data);
Tl=T.left; // left child
T.left=Tl.right; // our left child is now what our left was pointing to
Tl.right=T; // move T down to the right
UpdateHeight(Tl.right); // update the height of T
UpdateHeight(Tl); // update hte height of the new root
return Tl;
} // of RightRotate
public AVL() {
root=null;
} // of constructor AVL
// method to allow external entity to insert an element into the tree
public void insert(int D)
{
root=insert_internal(D, root);
} // of insert
private Node insert_internal(int D, Node T) {
if (T==null) return( new Node (D, null, null, 0));
if (T.data == D) return T; // the data is already in there
if ( D < T. data ) // go left
{ if (T.left == null)
{
T.left = insert_internal(D,null);
UpdateHeight(T);
}
else { //interior node
T.left = insert_internal(D, T.left);
}
} // of go left
else // D goes to the right
{ if (T.right == null)
{
T.right = insert_internal(D,null);
UpdateHeight(T);
}
else { //interior node
T.right = insert_internal(D, T.right);
}
} // of go right
// now we have to figure out if things are out of
// balance
int diff= HEIGHT(T.right) - HEIGHT(T.left);
System.out.println("difference is " + diff + " data is " + T.data);
if ( Math.abs(diff) <= 1) // we are good to go at this level
{
UpdateHeight(T);
return(T);
}
// only if diff is bigger than 1
if ( diff > 1)// right leaning
{ // look at right child and figure out how it is leaning
} // of right leaning
else // left leaning
{ // look at left child to see how it is leaning
Node child = T.left;
int cdiff;
cdiff = HEIGHT(child.right) - HEIGHT(child.left);
System.out.println("cdiff is " + cdiff);
if ( cdiff < 0 ) // left left lean
{ T=RightRotate(T); }
else
{
System.out.println("SHAUN");
preorder_internal(T);
T.left = LeftRotate(T.left);
System.out.println("SHAUN");
preorder_internal(T);
T=RightRotate(T);
}
} // of left leaning
// at this point we have rotated, so we need to update
// the height of our current tree
UpdateHeight(T);
return(T);
} // of insert_internal
public void preorder() {
System.out.println("preorder");
preorder_internal(root);
} // of preorder
private void preorder_internal(Node T) {
if (T==null) return;
else { System.out.println(T.data + " height " + T.height);
preorder_internal(T.left);
preorder_internal(T.right);
return;
} // of else
} // or preorder_internal
}// of AVL
class avltester {
public static void main(String args[]) {
AVL T;
T=new AVL();
T.insert(5);
T.preorder();
T.insert(3);
T.preorder();
T.insert(4);
T.preorder();
} // of main
} // of avltester
class AVL {
Node root;
private class Node {
int data;
Node left, right;
int height;
private Node(int D, Node L, Node R, int H) {
data=D;
left=L;
right=R;
height=H; // user has to set height
} // of constructor Node
} //of Node
static private void UpdateHeight(Node T) {
if (T ==null) return;
else T.height = Math.max(HEIGHT(T.left),HEIGHT(T.right)) + 1;
} // UPdate Height
static private int HEIGHT(Node T) {
if (T== null ) return(-1);
else return (T.height);
}
// we need to more our right child up
static private Node LeftRotate(Node T) {
System.out.println("left rotate with data " + T.data);
Node Tr;
Tr=T.right; // right child
T.right=Tr.left; // our right child IS NOW hhh
Tr.left=T; // move T down to the left
UpdateHeight(Tr.left); // update the height of T
UpdateHeight(Tr); // update hte height of the new root
return Tr;
} // of LeftRotate
// we move our immediate left node up.
// in doing so, we are now immediat right of our left child
static private Node RightRotate(Node T) {
Node Tl;
System.out.println("left rotate with data " + T.data);
Tl=T.left; // left child
T.left=Tl.right; // our left child is now what our left was pointing to
Tl.right=T; // move T down to the right
UpdateHeight(Tl.right); // update the height of T
UpdateHeight(Tl); // update hte height of the new root
return Tl;
} // of RightRotate
public AVL() {
root=null;
} // of constructor AVL
// method to allow external entity to insert an element into the tree
public void insert(int D)
{
root=insert_internal(D, root);
} // of insert
private Node insert_internal(int D, Node T) {
if (T==null) return( new Node (D, null, null, 0));
if (T.data == D) return T; // the data is already in there
if ( D < T. data ) // go left
{ if (T.left == null)
{
T.left = insert_internal(D,null);
UpdateHeight(T);
}
else { //interior node
T.left = insert_internal(D, T.left);
}
} // of go left
else // D goes to the right
{ if (T.right == null)
{
T.right = insert_internal(D,null);
UpdateHeight(T);
}
else { //interior node
T.right = insert_internal(D, T.right);
}
} // of go right
// now we have to figure out if things are out of
// balance
int diff= HEIGHT(T.right) - HEIGHT(T.left);
System.out.println("difference is " + diff + " data is " + T.data);
if ( Math.abs(diff) <= 1) // we are good to go at this level
{
UpdateHeight(T);
return(T);
}
// only if diff is bigger than 1
if ( diff > 1)// right leaning
{ // look at right child and figure out how it is leaning
} // of right leaning
else // left leaning
{ // look at left child to see how it is leaning
Node child = T.left;
int cdiff;
cdiff = HEIGHT(child.right) - HEIGHT(child.left);
System.out.println("cdiff is " + cdiff);
if ( cdiff < 0 ) // left left lean
{ T=RightRotate(T); }
else
{
System.out.println("SHAUN");
preorder_internal(T);
T.left = LeftRotate(T.left);
System.out.println("SHAUN");
preorder_internal(T);
T=RightRotate(T);
}
} // of left leaning
// at this point we have rotated, so we need to update
// the height of our current tree
UpdateHeight(T);
return(T);
} // of insert_internal
public void preorder() {
System.out.println("preorder");
preorder_internal(root);
} // of preorder
private void preorder_internal(Node T) {
if (T==null) return;
else { System.out.println(T.data + " height " + T.height);
preorder_internal(T.left);
preorder_internal(T.right);
return;
} // of else
} // or preorder_internal
}// of AVL
class avltester {
public static void main(String args[]) {
AVL T;
T=new AVL();
T.insert(5);
T.preorder();
T.insert(3);
T.preorder();
T.insert(4);
T.preorder();
} // of main
} // of avltester
You are to create AVL tree code which implements the following methods insert (int D) delete
(int D) preorderprint() postorderprint0 inorderprint() Whenever an insertion or deletion occurs,
you are to rebalance the tree. You may use my code HERE as a starting point. There is no
guarantee that my code is correct. It implements a left insertion. You will need to implement
deletion using web resources, etc. (MAKE SURE YOU UNDERSTAND LEFT AND RIGHT
ROTATION One of these will be on the final exam).
Solution
AVL tree code implement : * Java Program to Implement AVL Tree */ import
java.util.Scanner; /* Class AVLNode */ class AVLNode /* Class AVLNode */
class AVLNode { AVLNode left, right; int data; int height; /*
Constructor */ public AVLNode() { left = null; right = null; data
= 0; height = 0; } /* Constructor */ public AVLNode(int n) {
left = null; right = null; data = n; height = 0; } } /* Class
AVLTree */ class AVLTree { private AVLNode root; /* Constructor */
public AVLTree() { root = null; } /* Function to check if tree is empty */
public boolean isEmpty() { return root == null; } /* Make the tree
logically empty */ public void makeEmpty() { root = null; } /*
Function to insert data */ public void insert(int data) { root = insert(data, root);
} /* Function to get height of node */ private int height(AVLNode t ) {
return t == null ? -1 : t.height; } /* Function to max of left/right node */ private int
max(int lhs, int rhs) { return lhs > rhs ? lhs : rhs; } /* Function to insert
data recursively */ private AVLNode insert(int x, AVLNode t) { if (t == null)
t = new AVLNode(x); else if (x < t.data) { t.left = insert( x, t.left
); if( height( t.left ) - height( t.right ) == 2 ) if( x < t.left.data )
t = rotateWithLeftChild( t ); else t = doubleWithLeftChild( t );
} else if( x > t.data ) { t.right = insert( x, t.right ); if( height(
t.right ) - height( t.left ) == 2 ) if( x > t.right.data) t =
rotateWithRightChild( t ); else t = doubleWithRightChild( t );
} else ; // Duplicate; do nothing t.height = max( height( t.left ), height(
t.right ) ) + 1; return t; } /* Rotate binary tree node with left child */
private AVLNode rotateWithLeftChild(AVLNode k2) { AVLNode k1 = k2.left;
k2.left = k1.right; k1.right = k2; k2.height = max( height( k2.left ), height(
k2.right ) ) + 1; k1.height = max( height( k1.left ), k2.height ) + 1; return k1;
} /* Rotate binary tree node with right child */ private AVLNode
rotateWithRightChild(AVLNode k1) { AVLNode k2 = k1.right; k1.right =
k2.left; k2.left = k1; k1.height = max( height( k1.left ), height( k1.right ) ) + 1;
k2.height = max( height( k2.right ), k1.height ) + 1; return k2; } /** *
Double rotate binary tree node: first left child * with its right child; then node k3 with new
left child */ private AVLNode doubleWithLeftChild(AVLNode k3) { k3.left =
rotateWithRightChild( k3.left ); return rotateWithLeftChild( k3 ); } /** *
Double rotate binary tree node: first right child * with its left child; then node k1 with new
right child */ private AVLNode doubleWithRightChild(AVLNode k1) {
k1.right = rotateWithLeftChild( k1.right ); return rotateWithRightChild( k1 ); }
/* Functions to count number of nodes */ public int countNodes() { return
countNodes(root); } private int countNodes(AVLNode r) { if (r == null)
return 0; else { int l = 1; l += countNodes(r.left);
l += countNodes(r.right); return l; } } /* Functions to search for an
element */ public boolean search(int val) { return search(root, val); }
private boolean search(AVLNode r, int val) { boolean found = false; while
((r != null) && !found) { int rval = r.data; if (val < rval) r
= r.left; else if (val > rval) r = r.right; else {
found = true; break; } found = search(r, val); }
return found; } /* Function for inorder traversal */ public void inorder() {
inorder(root); } private void inorder(AVLNode r) { if (r != null)
{ inorder(r.left); System.out.print(r.data +" "); inorder(r.right);
} } /* Function for preorder traversal */ public void preorder() {
preorder(root); } private void preorder(AVLNode r) { if (r != null)
{ System.out.print(r.data +" "); preorder(r.left);
preorder(r.right); } } /* Function for postorder traversal */ public void
postorder() { postorder(root); } private void postorder(AVLNode r) {
if (r != null) { postorder(r.left); postorder(r.right);
System.out.print(r.data +" "); } } } /* Class AVL Tree Test */
public class AVLTreeTest { public static void main(String[] args) {
Scanner scan = new Scanner(System.in); /* Creating object of AVLTree */
AVLTree avlt = new AVLTree(); System.out.println("AVLTree Tree Test ");
char ch; /* Perform tree operations */ do {
System.out.println(" AVLTree Operations "); System.out.println("1. insert ");
System.out.println("2. search"); System.out.println("3. count nodes");
System.out.println("4. check empty"); System.out.println("5. clear tree");
int choice = scan.nextInt(); switch (choice) { case 1 :
System.out.println("Enter integer element to insert"); avlt.insert( scan.nextInt()
); break; case 2 :
System.out.println("Enter integer element to search"); System.out.println("Search
result : "+ avlt.search( scan.nextInt() )); break;
case 3 : System.out.println("Nodes = "+ avlt.countNodes()); break;
case 4 : System.out.println("Empty status = "+ avlt.isEmpty());
break; case 5 : System.out.println(" Tree Cleared");
avlt.makeEmpty(); break; default :
System.out.println("Wrong Entry  "); break; } /* Display tree
*/ System.out.print(" Post order : "); avlt.postorder();
System.out.print(" Pre order : "); avlt.preorder(); System.out.print(" In
order : "); avlt.inorder(); System.out.println(" Do you want to continue
(Type y or n)  "); ch = scan.next().charAt(0); } while (ch ==
'Y'|| ch == 'y'); }

More Related Content

Similar to Here is the code given in the instructionsclass AVL {.pdf

Given BinaryNode.javapackage util;import java.util.;T.pdf
Given BinaryNode.javapackage util;import java.util.;T.pdfGiven BinaryNode.javapackage util;import java.util.;T.pdf
Given BinaryNode.javapackage util;import java.util.;T.pdfConint29
 
write a method to generate AVL tree of height h wth fewest nodes and.pdf
write a method to generate AVL tree of height h wth fewest nodes and.pdfwrite a method to generate AVL tree of height h wth fewest nodes and.pdf
write a method to generate AVL tree of height h wth fewest nodes and.pdfarcotstarsports
 
import javautilQueue import javautilLinkedList import .pdf
import javautilQueue import javautilLinkedList import .pdfimport javautilQueue import javautilLinkedList import .pdf
import javautilQueue import javautilLinkedList import .pdfADITIEYEWEAR
 
My C proggram is having trouble in the switch in main. Also the a co.pdf
My C proggram is having trouble in the switch in main. Also the a co.pdfMy C proggram is having trouble in the switch in main. Also the a co.pdf
My C proggram is having trouble in the switch in main. Also the a co.pdfmeerobertsonheyde608
 
package DataStructures; public class HelloWorld AnyType extends.pdf
package DataStructures; public class HelloWorld AnyType extends.pdfpackage DataStructures; public class HelloWorld AnyType extends.pdf
package DataStructures; public class HelloWorld AnyType extends.pdfapleathers
 
A perfect left-sided binary tree is a binary tree where every intern.pdf
A perfect left-sided binary tree is a binary tree where every intern.pdfA perfect left-sided binary tree is a binary tree where every intern.pdf
A perfect left-sided binary tree is a binary tree where every intern.pdfmichardsonkhaicarr37
 
Write a program that accepts an arithmetic expression of unsigned in.pdf
Write a program that accepts an arithmetic expression of unsigned in.pdfWrite a program that accepts an arithmetic expression of unsigned in.pdf
Write a program that accepts an arithmetic expression of unsigned in.pdfJUSTSTYLISH3B2MOHALI
 
Questions has 4 parts.1st part Program to implement sorting algor.pdf
Questions has 4 parts.1st part Program to implement sorting algor.pdfQuestions has 4 parts.1st part Program to implement sorting algor.pdf
Questions has 4 parts.1st part Program to implement sorting algor.pdfapexelectronices01
 
JAVA A double-ended queue is a list that allows the addition and.pdf
JAVA A double-ended queue is a list that allows the addition and.pdfJAVA A double-ended queue is a list that allows the addition and.pdf
JAVA A double-ended queue is a list that allows the addition and.pdfamrishinda
 
public class AVLTreeT extends ComparableT extends BSTT { p.pdf
public class AVLTreeT extends ComparableT extends BSTT {   p.pdfpublic class AVLTreeT extends ComparableT extends BSTT {   p.pdf
public class AVLTreeT extends ComparableT extends BSTT { p.pdfagmobiles
 
#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docx#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docxajoy21
 
C++ QUICK REFERENCE.pdf
C++ QUICK REFERENCE.pdfC++ QUICK REFERENCE.pdf
C++ QUICK REFERENCE.pdffqerwqdfad
 
CppQuickRef.pdf
CppQuickRef.pdfCppQuickRef.pdf
CppQuickRef.pdfkurimaru1
 
Using the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdfUsing the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdfconnellalykshamesb60
 
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docx
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docxAvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docx
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docxrock73
 

Similar to Here is the code given in the instructionsclass AVL {.pdf (20)

Given BinaryNode.javapackage util;import java.util.;T.pdf
Given BinaryNode.javapackage util;import java.util.;T.pdfGiven BinaryNode.javapackage util;import java.util.;T.pdf
Given BinaryNode.javapackage util;import java.util.;T.pdf
 
write a method to generate AVL tree of height h wth fewest nodes and.pdf
write a method to generate AVL tree of height h wth fewest nodes and.pdfwrite a method to generate AVL tree of height h wth fewest nodes and.pdf
write a method to generate AVL tree of height h wth fewest nodes and.pdf
 
week-14x
week-14xweek-14x
week-14x
 
import javautilQueue import javautilLinkedList import .pdf
import javautilQueue import javautilLinkedList import .pdfimport javautilQueue import javautilLinkedList import .pdf
import javautilQueue import javautilLinkedList import .pdf
 
DAA Lab Work.docx
DAA Lab Work.docxDAA Lab Work.docx
DAA Lab Work.docx
 
My C proggram is having trouble in the switch in main. Also the a co.pdf
My C proggram is having trouble in the switch in main. Also the a co.pdfMy C proggram is having trouble in the switch in main. Also the a co.pdf
My C proggram is having trouble in the switch in main. Also the a co.pdf
 
package DataStructures; public class HelloWorld AnyType extends.pdf
package DataStructures; public class HelloWorld AnyType extends.pdfpackage DataStructures; public class HelloWorld AnyType extends.pdf
package DataStructures; public class HelloWorld AnyType extends.pdf
 
A perfect left-sided binary tree is a binary tree where every intern.pdf
A perfect left-sided binary tree is a binary tree where every intern.pdfA perfect left-sided binary tree is a binary tree where every intern.pdf
A perfect left-sided binary tree is a binary tree where every intern.pdf
 
Write a program that accepts an arithmetic expression of unsigned in.pdf
Write a program that accepts an arithmetic expression of unsigned in.pdfWrite a program that accepts an arithmetic expression of unsigned in.pdf
Write a program that accepts an arithmetic expression of unsigned in.pdf
 
Questions has 4 parts.1st part Program to implement sorting algor.pdf
Questions has 4 parts.1st part Program to implement sorting algor.pdfQuestions has 4 parts.1st part Program to implement sorting algor.pdf
Questions has 4 parts.1st part Program to implement sorting algor.pdf
 
week-17x
week-17xweek-17x
week-17x
 
week-18x
week-18xweek-18x
week-18x
 
JAVA A double-ended queue is a list that allows the addition and.pdf
JAVA A double-ended queue is a list that allows the addition and.pdfJAVA A double-ended queue is a list that allows the addition and.pdf
JAVA A double-ended queue is a list that allows the addition and.pdf
 
public class AVLTreeT extends ComparableT extends BSTT { p.pdf
public class AVLTreeT extends ComparableT extends BSTT {   p.pdfpublic class AVLTreeT extends ComparableT extends BSTT {   p.pdf
public class AVLTreeT extends ComparableT extends BSTT { p.pdf
 
#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docx#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docx
 
C++ QUICK REFERENCE.pdf
C++ QUICK REFERENCE.pdfC++ QUICK REFERENCE.pdf
C++ QUICK REFERENCE.pdf
 
CppQuickRef.pdf
CppQuickRef.pdfCppQuickRef.pdf
CppQuickRef.pdf
 
Unit - 2.pdf
Unit - 2.pdfUnit - 2.pdf
Unit - 2.pdf
 
Using the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdfUsing the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdf
 
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docx
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docxAvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docx
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docx
 

More from manjan6

An introduction and explanation of human factors and sociotechnical .pdf
An introduction and explanation of human factors and sociotechnical .pdfAn introduction and explanation of human factors and sociotechnical .pdf
An introduction and explanation of human factors and sociotechnical .pdfmanjan6
 
Astronomers were able to find a new planet in a far away solar system.pdf
Astronomers were able to find a new planet in a far away solar system.pdfAstronomers were able to find a new planet in a far away solar system.pdf
Astronomers were able to find a new planet in a far away solar system.pdfmanjan6
 
5. If we found AB+ blood at a crime scene and we knew one of our 5 s.pdf
5. If we found AB+ blood at a crime scene and we knew one of our 5 s.pdf5. If we found AB+ blood at a crime scene and we knew one of our 5 s.pdf
5. If we found AB+ blood at a crime scene and we knew one of our 5 s.pdfmanjan6
 
All of the following individuals are U.S. residents Kelly (27.pdf
All of the following individuals are U.S. residents Kelly (27.pdfAll of the following individuals are U.S. residents Kelly (27.pdf
All of the following individuals are U.S. residents Kelly (27.pdfmanjan6
 
Blossom Company had these transactions during the current period..pdf
Blossom Company had these transactions during the current period..pdfBlossom Company had these transactions during the current period..pdf
Blossom Company had these transactions during the current period..pdfmanjan6
 
Using the case study below, develop a written report of your market .pdf
Using the case study below, develop a written report of your market .pdfUsing the case study below, develop a written report of your market .pdf
Using the case study below, develop a written report of your market .pdfmanjan6
 
Which of the following is NOT a characteristic of a plasmid used as .pdf
Which of the following is NOT a characteristic of a plasmid used as .pdfWhich of the following is NOT a characteristic of a plasmid used as .pdf
Which of the following is NOT a characteristic of a plasmid used as .pdfmanjan6
 
What is the evolutionary significance of the amniotic egg Solut.pdf
What is the evolutionary significance of the amniotic egg  Solut.pdfWhat is the evolutionary significance of the amniotic egg  Solut.pdf
What is the evolutionary significance of the amniotic egg Solut.pdfmanjan6
 
What is the role of HTTP What types of objects are transmitted in H.pdf
What is the role of HTTP What types of objects are transmitted in H.pdfWhat is the role of HTTP What types of objects are transmitted in H.pdf
What is the role of HTTP What types of objects are transmitted in H.pdfmanjan6
 
What is the difference between a hash in perl and a hashtable in Jav.pdf
What is the difference between a hash in perl and a hashtable in Jav.pdfWhat is the difference between a hash in perl and a hashtable in Jav.pdf
What is the difference between a hash in perl and a hashtable in Jav.pdfmanjan6
 
What are the specific linkages among immune surveillance, clonal sel.pdf
What are the specific linkages among immune surveillance, clonal sel.pdfWhat are the specific linkages among immune surveillance, clonal sel.pdf
What are the specific linkages among immune surveillance, clonal sel.pdfmanjan6
 
True or False –Paraeducators provide direct or indirect instructio.pdf
True or False –Paraeducators provide direct or indirect instructio.pdfTrue or False –Paraeducators provide direct or indirect instructio.pdf
True or False –Paraeducators provide direct or indirect instructio.pdfmanjan6
 
The situation where the few who yell the loudest get heard Is ref.pdf
The situation where the few who yell the loudest get heard Is ref.pdfThe situation where the few who yell the loudest get heard Is ref.pdf
The situation where the few who yell the loudest get heard Is ref.pdfmanjan6
 
Templated Binary Tree implementing function help I need to im.pdf
Templated Binary Tree implementing function help I need to im.pdfTemplated Binary Tree implementing function help I need to im.pdf
Templated Binary Tree implementing function help I need to im.pdfmanjan6
 
State if you agree or disagree with the question and comments made b.pdf
State if you agree or disagree with the question and comments made b.pdfState if you agree or disagree with the question and comments made b.pdf
State if you agree or disagree with the question and comments made b.pdfmanjan6
 
A number of benefits that one might expect to see from using a datab.pdf
A number of benefits that one might expect to see from using a datab.pdfA number of benefits that one might expect to see from using a datab.pdf
A number of benefits that one might expect to see from using a datab.pdfmanjan6
 
QUESTION If you look at the code, youll see that we keep two list.pdf
QUESTION If you look at the code, youll see that we keep two list.pdfQUESTION If you look at the code, youll see that we keep two list.pdf
QUESTION If you look at the code, youll see that we keep two list.pdfmanjan6
 
Question 11 What is the volume of 17.0 grams of carbon dioxide gas if.pdf
Question 11 What is the volume of 17.0 grams of carbon dioxide gas if.pdfQuestion 11 What is the volume of 17.0 grams of carbon dioxide gas if.pdf
Question 11 What is the volume of 17.0 grams of carbon dioxide gas if.pdfmanjan6
 
Please help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdfPlease help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdfmanjan6
 
Match the enzyme activity in DNA synthesis with its function. DNA po.pdf
Match the enzyme activity in DNA synthesis with its function.  DNA po.pdfMatch the enzyme activity in DNA synthesis with its function.  DNA po.pdf
Match the enzyme activity in DNA synthesis with its function. DNA po.pdfmanjan6
 

More from manjan6 (20)

An introduction and explanation of human factors and sociotechnical .pdf
An introduction and explanation of human factors and sociotechnical .pdfAn introduction and explanation of human factors and sociotechnical .pdf
An introduction and explanation of human factors and sociotechnical .pdf
 
Astronomers were able to find a new planet in a far away solar system.pdf
Astronomers were able to find a new planet in a far away solar system.pdfAstronomers were able to find a new planet in a far away solar system.pdf
Astronomers were able to find a new planet in a far away solar system.pdf
 
5. If we found AB+ blood at a crime scene and we knew one of our 5 s.pdf
5. If we found AB+ blood at a crime scene and we knew one of our 5 s.pdf5. If we found AB+ blood at a crime scene and we knew one of our 5 s.pdf
5. If we found AB+ blood at a crime scene and we knew one of our 5 s.pdf
 
All of the following individuals are U.S. residents Kelly (27.pdf
All of the following individuals are U.S. residents Kelly (27.pdfAll of the following individuals are U.S. residents Kelly (27.pdf
All of the following individuals are U.S. residents Kelly (27.pdf
 
Blossom Company had these transactions during the current period..pdf
Blossom Company had these transactions during the current period..pdfBlossom Company had these transactions during the current period..pdf
Blossom Company had these transactions during the current period..pdf
 
Using the case study below, develop a written report of your market .pdf
Using the case study below, develop a written report of your market .pdfUsing the case study below, develop a written report of your market .pdf
Using the case study below, develop a written report of your market .pdf
 
Which of the following is NOT a characteristic of a plasmid used as .pdf
Which of the following is NOT a characteristic of a plasmid used as .pdfWhich of the following is NOT a characteristic of a plasmid used as .pdf
Which of the following is NOT a characteristic of a plasmid used as .pdf
 
What is the evolutionary significance of the amniotic egg Solut.pdf
What is the evolutionary significance of the amniotic egg  Solut.pdfWhat is the evolutionary significance of the amniotic egg  Solut.pdf
What is the evolutionary significance of the amniotic egg Solut.pdf
 
What is the role of HTTP What types of objects are transmitted in H.pdf
What is the role of HTTP What types of objects are transmitted in H.pdfWhat is the role of HTTP What types of objects are transmitted in H.pdf
What is the role of HTTP What types of objects are transmitted in H.pdf
 
What is the difference between a hash in perl and a hashtable in Jav.pdf
What is the difference between a hash in perl and a hashtable in Jav.pdfWhat is the difference between a hash in perl and a hashtable in Jav.pdf
What is the difference between a hash in perl and a hashtable in Jav.pdf
 
What are the specific linkages among immune surveillance, clonal sel.pdf
What are the specific linkages among immune surveillance, clonal sel.pdfWhat are the specific linkages among immune surveillance, clonal sel.pdf
What are the specific linkages among immune surveillance, clonal sel.pdf
 
True or False –Paraeducators provide direct or indirect instructio.pdf
True or False –Paraeducators provide direct or indirect instructio.pdfTrue or False –Paraeducators provide direct or indirect instructio.pdf
True or False –Paraeducators provide direct or indirect instructio.pdf
 
The situation where the few who yell the loudest get heard Is ref.pdf
The situation where the few who yell the loudest get heard Is ref.pdfThe situation where the few who yell the loudest get heard Is ref.pdf
The situation where the few who yell the loudest get heard Is ref.pdf
 
Templated Binary Tree implementing function help I need to im.pdf
Templated Binary Tree implementing function help I need to im.pdfTemplated Binary Tree implementing function help I need to im.pdf
Templated Binary Tree implementing function help I need to im.pdf
 
State if you agree or disagree with the question and comments made b.pdf
State if you agree or disagree with the question and comments made b.pdfState if you agree or disagree with the question and comments made b.pdf
State if you agree or disagree with the question and comments made b.pdf
 
A number of benefits that one might expect to see from using a datab.pdf
A number of benefits that one might expect to see from using a datab.pdfA number of benefits that one might expect to see from using a datab.pdf
A number of benefits that one might expect to see from using a datab.pdf
 
QUESTION If you look at the code, youll see that we keep two list.pdf
QUESTION If you look at the code, youll see that we keep two list.pdfQUESTION If you look at the code, youll see that we keep two list.pdf
QUESTION If you look at the code, youll see that we keep two list.pdf
 
Question 11 What is the volume of 17.0 grams of carbon dioxide gas if.pdf
Question 11 What is the volume of 17.0 grams of carbon dioxide gas if.pdfQuestion 11 What is the volume of 17.0 grams of carbon dioxide gas if.pdf
Question 11 What is the volume of 17.0 grams of carbon dioxide gas if.pdf
 
Please help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdfPlease help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdf
 
Match the enzyme activity in DNA synthesis with its function. DNA po.pdf
Match the enzyme activity in DNA synthesis with its function.  DNA po.pdfMatch the enzyme activity in DNA synthesis with its function.  DNA po.pdf
Match the enzyme activity in DNA synthesis with its function. DNA po.pdf
 

Recently uploaded

Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxNikitaBankoti2
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 

Recently uploaded (20)

Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 

Here is the code given in the instructionsclass AVL {.pdf

  • 1. Here is the code given in the instructions: class AVL { Node root; private class Node { int data; Node left, right; int height; private Node(int D, Node L, Node R, int H) { data=D; left=L; right=R; height=H; // user has to set height } // of constructor Node } //of Node static private void UpdateHeight(Node T) { if (T ==null) return; else T.height = Math.max(HEIGHT(T.left),HEIGHT(T.right)) + 1; } // UPdate Height static private int HEIGHT(Node T) { if (T== null ) return(-1); else return (T.height); } // we need to more our right child up static private Node LeftRotate(Node T) {
  • 2. System.out.println("left rotate with data " + T.data); Node Tr; Tr=T.right; // right child T.right=Tr.left; // our right child IS NOW hhh Tr.left=T; // move T down to the left UpdateHeight(Tr.left); // update the height of T UpdateHeight(Tr); // update hte height of the new root return Tr; } // of LeftRotate // we move our immediate left node up. // in doing so, we are now immediat right of our left child static private Node RightRotate(Node T) { Node Tl; System.out.println("left rotate with data " + T.data); Tl=T.left; // left child T.left=Tl.right; // our left child is now what our left was pointing to Tl.right=T; // move T down to the right UpdateHeight(Tl.right); // update the height of T UpdateHeight(Tl); // update hte height of the new root return Tl; } // of RightRotate public AVL() { root=null; } // of constructor AVL
  • 3. // method to allow external entity to insert an element into the tree public void insert(int D) { root=insert_internal(D, root); } // of insert private Node insert_internal(int D, Node T) { if (T==null) return( new Node (D, null, null, 0)); if (T.data == D) return T; // the data is already in there if ( D < T. data ) // go left { if (T.left == null) { T.left = insert_internal(D,null); UpdateHeight(T); } else { //interior node T.left = insert_internal(D, T.left); } } // of go left else // D goes to the right { if (T.right == null) { T.right = insert_internal(D,null); UpdateHeight(T); } else { //interior node T.right = insert_internal(D, T.right); } } // of go right
  • 4. // now we have to figure out if things are out of // balance int diff= HEIGHT(T.right) - HEIGHT(T.left); System.out.println("difference is " + diff + " data is " + T.data); if ( Math.abs(diff) <= 1) // we are good to go at this level { UpdateHeight(T); return(T); } // only if diff is bigger than 1 if ( diff > 1)// right leaning { // look at right child and figure out how it is leaning } // of right leaning else // left leaning { // look at left child to see how it is leaning Node child = T.left; int cdiff; cdiff = HEIGHT(child.right) - HEIGHT(child.left); System.out.println("cdiff is " + cdiff); if ( cdiff < 0 ) // left left lean { T=RightRotate(T); } else
  • 5. { System.out.println("SHAUN"); preorder_internal(T); T.left = LeftRotate(T.left); System.out.println("SHAUN"); preorder_internal(T); T=RightRotate(T); } } // of left leaning // at this point we have rotated, so we need to update // the height of our current tree UpdateHeight(T); return(T); } // of insert_internal public void preorder() { System.out.println("preorder"); preorder_internal(root); } // of preorder private void preorder_internal(Node T) { if (T==null) return; else { System.out.println(T.data + " height " + T.height); preorder_internal(T.left); preorder_internal(T.right); return;
  • 6. } // of else } // or preorder_internal }// of AVL class avltester { public static void main(String args[]) { AVL T; T=new AVL(); T.insert(5); T.preorder(); T.insert(3); T.preorder(); T.insert(4); T.preorder(); } // of main } // of avltester class AVL { Node root; private class Node {
  • 7. int data; Node left, right; int height; private Node(int D, Node L, Node R, int H) { data=D; left=L; right=R; height=H; // user has to set height } // of constructor Node } //of Node static private void UpdateHeight(Node T) { if (T ==null) return; else T.height = Math.max(HEIGHT(T.left),HEIGHT(T.right)) + 1; } // UPdate Height static private int HEIGHT(Node T) { if (T== null ) return(-1); else return (T.height); } // we need to more our right child up static private Node LeftRotate(Node T) { System.out.println("left rotate with data " + T.data); Node Tr; Tr=T.right; // right child T.right=Tr.left; // our right child IS NOW hhh Tr.left=T; // move T down to the left UpdateHeight(Tr.left); // update the height of T UpdateHeight(Tr); // update hte height of the new root return Tr;
  • 8. } // of LeftRotate // we move our immediate left node up. // in doing so, we are now immediat right of our left child static private Node RightRotate(Node T) { Node Tl; System.out.println("left rotate with data " + T.data); Tl=T.left; // left child T.left=Tl.right; // our left child is now what our left was pointing to Tl.right=T; // move T down to the right UpdateHeight(Tl.right); // update the height of T UpdateHeight(Tl); // update hte height of the new root return Tl; } // of RightRotate public AVL() { root=null; } // of constructor AVL // method to allow external entity to insert an element into the tree public void insert(int D) { root=insert_internal(D, root); } // of insert private Node insert_internal(int D, Node T) {
  • 9. if (T==null) return( new Node (D, null, null, 0)); if (T.data == D) return T; // the data is already in there if ( D < T. data ) // go left { if (T.left == null) { T.left = insert_internal(D,null); UpdateHeight(T); } else { //interior node T.left = insert_internal(D, T.left); } } // of go left else // D goes to the right { if (T.right == null) { T.right = insert_internal(D,null); UpdateHeight(T); } else { //interior node T.right = insert_internal(D, T.right); } } // of go right // now we have to figure out if things are out of // balance int diff= HEIGHT(T.right) - HEIGHT(T.left); System.out.println("difference is " + diff + " data is " + T.data);
  • 10. if ( Math.abs(diff) <= 1) // we are good to go at this level { UpdateHeight(T); return(T); } // only if diff is bigger than 1 if ( diff > 1)// right leaning { // look at right child and figure out how it is leaning } // of right leaning else // left leaning { // look at left child to see how it is leaning Node child = T.left; int cdiff; cdiff = HEIGHT(child.right) - HEIGHT(child.left); System.out.println("cdiff is " + cdiff); if ( cdiff < 0 ) // left left lean { T=RightRotate(T); } else { System.out.println("SHAUN"); preorder_internal(T); T.left = LeftRotate(T.left); System.out.println("SHAUN"); preorder_internal(T); T=RightRotate(T); }
  • 11. } // of left leaning // at this point we have rotated, so we need to update // the height of our current tree UpdateHeight(T); return(T); } // of insert_internal public void preorder() { System.out.println("preorder"); preorder_internal(root); } // of preorder private void preorder_internal(Node T) { if (T==null) return; else { System.out.println(T.data + " height " + T.height); preorder_internal(T.left); preorder_internal(T.right); return; } // of else } // or preorder_internal }// of AVL class avltester {
  • 12. public static void main(String args[]) { AVL T; T=new AVL(); T.insert(5); T.preorder(); T.insert(3); T.preorder(); T.insert(4); T.preorder(); } // of main } // of avltester You are to create AVL tree code which implements the following methods insert (int D) delete (int D) preorderprint() postorderprint0 inorderprint() Whenever an insertion or deletion occurs, you are to rebalance the tree. You may use my code HERE as a starting point. There is no guarantee that my code is correct. It implements a left insertion. You will need to implement deletion using web resources, etc. (MAKE SURE YOU UNDERSTAND LEFT AND RIGHT ROTATION One of these will be on the final exam). Solution AVL tree code implement : * Java Program to Implement AVL Tree */ import java.util.Scanner; /* Class AVLNode */ class AVLNode /* Class AVLNode */ class AVLNode { AVLNode left, right; int data; int height; /* Constructor */ public AVLNode() { left = null; right = null; data
  • 13. = 0; height = 0; } /* Constructor */ public AVLNode(int n) { left = null; right = null; data = n; height = 0; } } /* Class AVLTree */ class AVLTree { private AVLNode root; /* Constructor */ public AVLTree() { root = null; } /* Function to check if tree is empty */ public boolean isEmpty() { return root == null; } /* Make the tree logically empty */ public void makeEmpty() { root = null; } /* Function to insert data */ public void insert(int data) { root = insert(data, root); } /* Function to get height of node */ private int height(AVLNode t ) { return t == null ? -1 : t.height; } /* Function to max of left/right node */ private int max(int lhs, int rhs) { return lhs > rhs ? lhs : rhs; } /* Function to insert data recursively */ private AVLNode insert(int x, AVLNode t) { if (t == null) t = new AVLNode(x); else if (x < t.data) { t.left = insert( x, t.left ); if( height( t.left ) - height( t.right ) == 2 ) if( x < t.left.data ) t = rotateWithLeftChild( t ); else t = doubleWithLeftChild( t ); } else if( x > t.data ) { t.right = insert( x, t.right ); if( height( t.right ) - height( t.left ) == 2 ) if( x > t.right.data) t = rotateWithRightChild( t ); else t = doubleWithRightChild( t ); } else ; // Duplicate; do nothing t.height = max( height( t.left ), height( t.right ) ) + 1; return t; } /* Rotate binary tree node with left child */ private AVLNode rotateWithLeftChild(AVLNode k2) { AVLNode k1 = k2.left; k2.left = k1.right; k1.right = k2; k2.height = max( height( k2.left ), height( k2.right ) ) + 1; k1.height = max( height( k1.left ), k2.height ) + 1; return k1; } /* Rotate binary tree node with right child */ private AVLNode rotateWithRightChild(AVLNode k1) { AVLNode k2 = k1.right; k1.right = k2.left; k2.left = k1; k1.height = max( height( k1.left ), height( k1.right ) ) + 1; k2.height = max( height( k2.right ), k1.height ) + 1; return k2; } /** * Double rotate binary tree node: first left child * with its right child; then node k3 with new left child */ private AVLNode doubleWithLeftChild(AVLNode k3) { k3.left = rotateWithRightChild( k3.left ); return rotateWithLeftChild( k3 ); } /** * Double rotate binary tree node: first right child * with its left child; then node k1 with new right child */ private AVLNode doubleWithRightChild(AVLNode k1) { k1.right = rotateWithLeftChild( k1.right ); return rotateWithRightChild( k1 ); } /* Functions to count number of nodes */ public int countNodes() { return countNodes(root); } private int countNodes(AVLNode r) { if (r == null) return 0; else { int l = 1; l += countNodes(r.left); l += countNodes(r.right); return l; } } /* Functions to search for an
  • 14. element */ public boolean search(int val) { return search(root, val); } private boolean search(AVLNode r, int val) { boolean found = false; while ((r != null) && !found) { int rval = r.data; if (val < rval) r = r.left; else if (val > rval) r = r.right; else { found = true; break; } found = search(r, val); } return found; } /* Function for inorder traversal */ public void inorder() { inorder(root); } private void inorder(AVLNode r) { if (r != null) { inorder(r.left); System.out.print(r.data +" "); inorder(r.right); } } /* Function for preorder traversal */ public void preorder() { preorder(root); } private void preorder(AVLNode r) { if (r != null) { System.out.print(r.data +" "); preorder(r.left); preorder(r.right); } } /* Function for postorder traversal */ public void postorder() { postorder(root); } private void postorder(AVLNode r) { if (r != null) { postorder(r.left); postorder(r.right); System.out.print(r.data +" "); } } } /* Class AVL Tree Test */ public class AVLTreeTest { public static void main(String[] args) { Scanner scan = new Scanner(System.in); /* Creating object of AVLTree */ AVLTree avlt = new AVLTree(); System.out.println("AVLTree Tree Test "); char ch; /* Perform tree operations */ do { System.out.println(" AVLTree Operations "); System.out.println("1. insert "); System.out.println("2. search"); System.out.println("3. count nodes"); System.out.println("4. check empty"); System.out.println("5. clear tree"); int choice = scan.nextInt(); switch (choice) { case 1 : System.out.println("Enter integer element to insert"); avlt.insert( scan.nextInt() ); break; case 2 : System.out.println("Enter integer element to search"); System.out.println("Search result : "+ avlt.search( scan.nextInt() )); break; case 3 : System.out.println("Nodes = "+ avlt.countNodes()); break; case 4 : System.out.println("Empty status = "+ avlt.isEmpty()); break; case 5 : System.out.println(" Tree Cleared"); avlt.makeEmpty(); break; default : System.out.println("Wrong Entry "); break; } /* Display tree */ System.out.print(" Post order : "); avlt.postorder(); System.out.print(" Pre order : "); avlt.preorder(); System.out.print(" In order : "); avlt.inorder(); System.out.println(" Do you want to continue (Type y or n) "); ch = scan.next().charAt(0); } while (ch ==
  • 15. 'Y'|| ch == 'y'); }