SlideShare a Scribd company logo
Count Red Nodes. Write a program that computes the percentage of red nodes in a given red-
black BST. Test your program by running at least 100 trials of the experiment of inserting N
random keys into an initially empty tree, for N = 10^4, 10^5, 10^6, and formulate an hypothesis.
*It is experiment from textbook Algorithms, 3.3.42
Does anyone know the answer?
Solution
/*
* Java Program to Implement Red Black Tree
*/
import java.util.Scanner;
/* Class Node */
class RedBlackNode
{
RedBlackNode left, right;
int element;
int color;
/* Constructor */
public RedBlackNode(int theElement)
{
this( theElement, null, null );
}
/* Constructor */
public RedBlackNode(int theElement, RedBlackNode lt, RedBlackNode rt)
{
left = lt;
right = rt;
element = theElement;
color = 1;
}
}
/* Class RBTree */
class RBTree
{
private RedBlackNode current;
private RedBlackNode parent;
private RedBlackNode grand;
private RedBlackNode great;
private RedBlackNode header;
private static RedBlackNode nullNode;
/* static initializer for nullNode */
static
{
nullNode = new RedBlackNode(0);
nullNode.left = nullNode;
nullNode.right = nullNode;
}
/* Black - 1 RED - 0 */
static final int BLACK = 1;
static final int RED = 0;
/* Constructor */
public RBTree(int negInf)
{
header = new RedBlackNode(negInf);
header.left = nullNode;
header.right = nullNode;
}
/* Function to check if tree is empty */
public boolean isEmpty()
{
return header.right == nullNode;
}
/* Make the tree logically empty */
public void makeEmpty()
{
header.right = nullNode;
}
/* Function to insert item */
public void insert(int item )
{
current = parent = grand = header;
nullNode.element = item;
while (current.element != item)
{
great = grand;
grand = parent;
parent = current;
current = item < current.element ? current.left : current.right;
// Check if two red children and fix if so
if (current.left.color == RED && current.right.color == RED)
handleReorient( item );
}
// Insertion fails if already present
if (current != nullNode)
return;
current = new RedBlackNode(item, nullNode, nullNode);
// Attach to parent
if (item < parent.element)
parent.left = current;
else
parent.right = current;
handleReorient( item );
}
private void handleReorient(int item)
{
// Do the color flip
current.color = RED;
current.left.color = BLACK;
current.right.color = BLACK;
if (parent.color == RED)
{
// Have to rotate
grand.color = RED;
if (item < grand.element != item < parent.element)
parent = rotate( item, grand ); // Start dbl rotate
current = rotate(item, great );
current.color = BLACK;
}
// Make root black
header.right.color = BLACK;
}
private RedBlackNode rotate(int item, RedBlackNode parent)
{
if(item < parent.element)
return parent.left = item < parent.left.element ? rotateWithLeftChild(parent.left) :
rotateWithRightChild(parent.left) ;
else
return parent.right = item < parent.right.element ? rotateWithLeftChild(parent.right) :
rotateWithRightChild(parent.right);
}
/* Rotate binary tree node with left child */
private RedBlackNode rotateWithLeftChild(RedBlackNode k2)
{
RedBlackNode k1 = k2.left;
k2.left = k1.right;
k1.right = k2;
return k1;
}
/* Rotate binary tree node with right child */
private RedBlackNode rotateWithRightChild(RedBlackNode k1)
{
RedBlackNode k2 = k1.right;
k1.right = k2.left;
k2.left = k1;
return k2;
}
/* Functions to count number of nodes */
public int countNodes()
{
return countNodes(header.right);
}
private int countNodes(RedBlackNode r)
{
if (r == nullNode)
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(header.right, val);
}
private boolean search(RedBlackNode r, int val)
{
boolean found = false;
while ((r != nullNode) && !found)
{
int rval = r.element;
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(header.right);
}
private void inorder(RedBlackNode r)
{
if (r != nullNode)
{
inorder(r.left);
char c = 'B';
if (r.color == 0)
c = 'R';
System.out.print(r.element +""+c+" ");
inorder(r.right);
}
}
/* Function for preorder traversal */
public void preorder()
{
preorder(header.right);
}
private void preorder(RedBlackNode r)
{
if (r != nullNode)
{
char c = 'B';
if (r.color == 0)
c = 'R';
System.out.print(r.element +""+c+" ");
preorder(r.left);
preorder(r.right);
}
}
/* Function for postorder traversal */
public void postorder()
{
postorder(header.right);
}
private void postorder(RedBlackNode r)
{
if (r != nullNode)
{
postorder(r.left);
postorder(r.right);
char c = 'B';
if (r.color == 0)
c = 'R';
System.out.print(r.element +""+c+" ");
}
}
}
/* Class RedBlackTreeTest */
public class RedBlackTreeTest
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
/* Creating object of RedBlack Tree */
RBTree rbt = new RBTree(Integer.MIN_VALUE);
System.out.println("Red Black Tree Test ");
char ch;
/* Perform tree operations */
do
{
System.out.println(" Red Black Tree 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");
rbt.insert( scan.nextInt() );
break;
case 2 :
System.out.println("Enter integer element to search");
System.out.println("Search result : "+ rbt.search( scan.nextInt() ));
break;
case 3 :
System.out.println("Nodes = "+ rbt.countNodes());
break;
case 4 :
System.out.println("Empty status = "+ rbt.isEmpty());
break;
case 5 :
System.out.println(" Tree Cleared");
rbt.makeEmpty();
break;
default :
System.out.println("Wrong Entry  ");
break;
}
/* Display tree */
System.out.print(" Post order : ");
rbt.postorder();
System.out.print(" Pre order : ");
rbt.preorder();
System.out.print(" In order : ");
rbt.inorder();
System.out.println(" Do you want to continue (Type y or n)  ");
ch = scan.next().charAt(0);
} while (ch == 'Y'|| ch == 'y');
}
}
OutPut:

More Related Content

Similar to Count Red Nodes. Write a program that computes the percentage of red.pdf

For the code below complete the preOrder() method so that it perform.pdf
For the code below complete the preOrder() method so that it perform.pdfFor the code below complete the preOrder() method so that it perform.pdf
For the code below complete the preOrder() method so that it perform.pdf
xlynettalampleyxc
 
Write a C program that reads the words the user types at the command.pdf
Write a C program that reads the words the user types at the command.pdfWrite a C program that reads the words the user types at the command.pdf
Write a C program that reads the words the user types at the command.pdf
SANDEEPARIHANT
 
C Homework Help
C Homework HelpC Homework Help
C Homework Help
Programming Homework Help
 
In this lab, you will be given a simple code for a min Heap, and you.pdf
In this lab, you will be given a simple code for a min Heap, and you.pdfIn this lab, you will be given a simple code for a min Heap, and you.pdf
In this lab, you will be given a simple code for a min Heap, and you.pdf
charanjit1717
 
a) Complete both insert and delete methods. If it works correctly 10.pdf
a) Complete both insert and delete methods. If it works correctly 10.pdfa) Complete both insert and delete methods. If it works correctly 10.pdf
a) Complete both insert and delete methods. If it works correctly 10.pdf
MAYANKBANSAL1981
 
Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdf
Please help write BinaryTree-java Thank you!   Create a class BinaryTr.pdfPlease help write BinaryTree-java Thank you!   Create a class BinaryTr.pdf
Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdf
info750646
 
usingpackage util;import java.util.;This class implements.pdf
usingpackage util;import java.util.;This class implements.pdfusingpackage util;import java.util.;This class implements.pdf
usingpackage util;import java.util.;This class implements.pdf
info335653
 
TDC2016POA | Trilha Programacao Funcional - Ramda JS como alternativa a under...
TDC2016POA | Trilha Programacao Funcional - Ramda JS como alternativa a under...TDC2016POA | Trilha Programacao Funcional - Ramda JS como alternativa a under...
TDC2016POA | Trilha Programacao Funcional - Ramda JS como alternativa a under...
tdc-globalcode
 
Ramda, a functional JavaScript library
Ramda, a functional JavaScript libraryRamda, a functional JavaScript library
Ramda, a functional JavaScript library
Derek Willian Stavis
 
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdfAssignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Footageetoffe16
 
JAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdfJAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdf
fantasiatheoutofthef
 
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
Conint29
 
C Exam Help
C Exam Help C Exam Help
C Exam Help
Programming Exam Help
 
How to do the main method for this programBinaryNode.javapublic.pdf
How to do the main method for this programBinaryNode.javapublic.pdfHow to do the main method for this programBinaryNode.javapublic.pdf
How to do the main method for this programBinaryNode.javapublic.pdf
feelingcomputors
 
Help I keep getting the same error when running a code. Below is the.pdf
Help I keep getting the same error when running a code. Below is the.pdfHelp I keep getting the same error when running a code. Below is the.pdf
Help I keep getting the same error when running a code. Below is the.pdf
mail931892
 
Wheels we didn't re-invent: Perl's Utility Modules
Wheels we didn't re-invent: Perl's Utility ModulesWheels we didn't re-invent: Perl's Utility Modules
Wheels we didn't re-invent: Perl's Utility Modules
Workhorse Computing
 
Given the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdfGiven the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdf
illyasraja7
 

Similar to Count Red Nodes. Write a program that computes the percentage of red.pdf (20)

For the code below complete the preOrder() method so that it perform.pdf
For the code below complete the preOrder() method so that it perform.pdfFor the code below complete the preOrder() method so that it perform.pdf
For the code below complete the preOrder() method so that it perform.pdf
 
week-14x
week-14xweek-14x
week-14x
 
Short intro to ECMAScript
Short intro to ECMAScriptShort intro to ECMAScript
Short intro to ECMAScript
 
Wakanday JS201 Best Practices
Wakanday JS201 Best PracticesWakanday JS201 Best Practices
Wakanday JS201 Best Practices
 
Write a C program that reads the words the user types at the command.pdf
Write a C program that reads the words the user types at the command.pdfWrite a C program that reads the words the user types at the command.pdf
Write a C program that reads the words the user types at the command.pdf
 
C Homework Help
C Homework HelpC Homework Help
C Homework Help
 
In this lab, you will be given a simple code for a min Heap, and you.pdf
In this lab, you will be given a simple code for a min Heap, and you.pdfIn this lab, you will be given a simple code for a min Heap, and you.pdf
In this lab, you will be given a simple code for a min Heap, and you.pdf
 
a) Complete both insert and delete methods. If it works correctly 10.pdf
a) Complete both insert and delete methods. If it works correctly 10.pdfa) Complete both insert and delete methods. If it works correctly 10.pdf
a) Complete both insert and delete methods. If it works correctly 10.pdf
 
Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdf
Please help write BinaryTree-java Thank you!   Create a class BinaryTr.pdfPlease help write BinaryTree-java Thank you!   Create a class BinaryTr.pdf
Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdf
 
usingpackage util;import java.util.;This class implements.pdf
usingpackage util;import java.util.;This class implements.pdfusingpackage util;import java.util.;This class implements.pdf
usingpackage util;import java.util.;This class implements.pdf
 
TDC2016POA | Trilha Programacao Funcional - Ramda JS como alternativa a under...
TDC2016POA | Trilha Programacao Funcional - Ramda JS como alternativa a under...TDC2016POA | Trilha Programacao Funcional - Ramda JS como alternativa a under...
TDC2016POA | Trilha Programacao Funcional - Ramda JS como alternativa a under...
 
Ramda, a functional JavaScript library
Ramda, a functional JavaScript libraryRamda, a functional JavaScript library
Ramda, a functional JavaScript library
 
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdfAssignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
 
JAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdfJAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.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.pdf
 
C Exam Help
C Exam Help C Exam Help
C Exam Help
 
How to do the main method for this programBinaryNode.javapublic.pdf
How to do the main method for this programBinaryNode.javapublic.pdfHow to do the main method for this programBinaryNode.javapublic.pdf
How to do the main method for this programBinaryNode.javapublic.pdf
 
Help I keep getting the same error when running a code. Below is the.pdf
Help I keep getting the same error when running a code. Below is the.pdfHelp I keep getting the same error when running a code. Below is the.pdf
Help I keep getting the same error when running a code. Below is the.pdf
 
Wheels we didn't re-invent: Perl's Utility Modules
Wheels we didn't re-invent: Perl's Utility ModulesWheels we didn't re-invent: Perl's Utility Modules
Wheels we didn't re-invent: Perl's Utility Modules
 
Given the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdfGiven the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdf
 

More from rozakashif85

Give background information concerning EMT and include what is known.pdf
Give background information concerning EMT and include what is known.pdfGive background information concerning EMT and include what is known.pdf
Give background information concerning EMT and include what is known.pdf
rozakashif85
 
Explain how the current economic recession differs from the depressio.pdf
Explain how the current economic recession differs from the depressio.pdfExplain how the current economic recession differs from the depressio.pdf
Explain how the current economic recession differs from the depressio.pdf
rozakashif85
 
Does yeast uses CopI and CopII formation for vesicle budding to grow.pdf
Does yeast uses CopI and CopII formation for vesicle budding to grow.pdfDoes yeast uses CopI and CopII formation for vesicle budding to grow.pdf
Does yeast uses CopI and CopII formation for vesicle budding to grow.pdf
rozakashif85
 
DNA molecules consist of chemically linked sequences of the bases ad.pdf
DNA molecules consist of chemically linked sequences of the bases ad.pdfDNA molecules consist of chemically linked sequences of the bases ad.pdf
DNA molecules consist of chemically linked sequences of the bases ad.pdf
rozakashif85
 
Data StructuresPLEASE USING THIS C++ PROGRAM BELOW, I NEED HEL.pdf
Data StructuresPLEASE USING THIS C++ PROGRAM BELOW, I NEED HEL.pdfData StructuresPLEASE USING THIS C++ PROGRAM BELOW, I NEED HEL.pdf
Data StructuresPLEASE USING THIS C++ PROGRAM BELOW, I NEED HEL.pdf
rozakashif85
 
apple 2008 historically what were Apples major competitive advanta.pdf
apple 2008 historically what were Apples major competitive advanta.pdfapple 2008 historically what were Apples major competitive advanta.pdf
apple 2008 historically what were Apples major competitive advanta.pdf
rozakashif85
 
A partial results from a PERT analysis for a project with 50 activit.pdf
A partial results from a PERT analysis for a project with 50 activit.pdfA partial results from a PERT analysis for a project with 50 activit.pdf
A partial results from a PERT analysis for a project with 50 activit.pdf
rozakashif85
 
briefly write about the variability of natural systems and the signi.pdf
briefly write about the variability of natural systems and the signi.pdfbriefly write about the variability of natural systems and the signi.pdf
briefly write about the variability of natural systems and the signi.pdf
rozakashif85
 
A graph is symmetric with respect to the vertical line corresponding.pdf
A graph is symmetric with respect to the vertical line corresponding.pdfA graph is symmetric with respect to the vertical line corresponding.pdf
A graph is symmetric with respect to the vertical line corresponding.pdf
rozakashif85
 
X-Linked Recessive Write three rules to keep in mind when counseling .pdf
X-Linked Recessive Write three rules to keep in mind when counseling .pdfX-Linked Recessive Write three rules to keep in mind when counseling .pdf
X-Linked Recessive Write three rules to keep in mind when counseling .pdf
rozakashif85
 
Write a Java Class to Implement a Generic Linked ListYour list mus.pdf
Write a Java Class to Implement a Generic Linked ListYour list mus.pdfWrite a Java Class to Implement a Generic Linked ListYour list mus.pdf
Write a Java Class to Implement a Generic Linked ListYour list mus.pdf
rozakashif85
 
Write a class (BasketballTeam) encapsulating the concept of a tea.pdf
Write a class (BasketballTeam) encapsulating the concept of a tea.pdfWrite a class (BasketballTeam) encapsulating the concept of a tea.pdf
Write a class (BasketballTeam) encapsulating the concept of a tea.pdf
rozakashif85
 
Which of the following would you expect to happen in a plant that doe.pdf
Which of the following would you expect to happen in a plant that doe.pdfWhich of the following would you expect to happen in a plant that doe.pdf
Which of the following would you expect to happen in a plant that doe.pdf
rozakashif85
 
What is the value of including personal information about yourself a.pdf
What is the value of including personal information about yourself a.pdfWhat is the value of including personal information about yourself a.pdf
What is the value of including personal information about yourself a.pdf
rozakashif85
 
What is a voluntary response sampleSolutionVoluntary response.pdf
What is a voluntary response sampleSolutionVoluntary response.pdfWhat is a voluntary response sampleSolutionVoluntary response.pdf
What is a voluntary response sampleSolutionVoluntary response.pdf
rozakashif85
 
What adaptive benefit do these abilities give wolbachia In oth.pdf
What adaptive benefit do these abilities give wolbachia In oth.pdfWhat adaptive benefit do these abilities give wolbachia In oth.pdf
What adaptive benefit do these abilities give wolbachia In oth.pdf
rozakashif85
 
Think about autumn (Fall season) in places like New England (Pennsyl.pdf
Think about autumn (Fall season) in places like New England (Pennsyl.pdfThink about autumn (Fall season) in places like New England (Pennsyl.pdf
Think about autumn (Fall season) in places like New England (Pennsyl.pdf
rozakashif85
 
The orange is which type of fruit Simple - Legume Simple - Drupe .pdf
The orange is which type of fruit  Simple - Legume  Simple - Drupe  .pdfThe orange is which type of fruit  Simple - Legume  Simple - Drupe  .pdf
The orange is which type of fruit Simple - Legume Simple - Drupe .pdf
rozakashif85
 
The _________ is the protective chamber that houses the ovule and Lat.pdf
The _________ is the protective chamber that houses the ovule and Lat.pdfThe _________ is the protective chamber that houses the ovule and Lat.pdf
The _________ is the protective chamber that houses the ovule and Lat.pdf
rozakashif85
 
Suppose X follows a normal distribution with mean=1 and variance=4. .pdf
Suppose X follows a normal distribution with mean=1 and variance=4. .pdfSuppose X follows a normal distribution with mean=1 and variance=4. .pdf
Suppose X follows a normal distribution with mean=1 and variance=4. .pdf
rozakashif85
 

More from rozakashif85 (20)

Give background information concerning EMT and include what is known.pdf
Give background information concerning EMT and include what is known.pdfGive background information concerning EMT and include what is known.pdf
Give background information concerning EMT and include what is known.pdf
 
Explain how the current economic recession differs from the depressio.pdf
Explain how the current economic recession differs from the depressio.pdfExplain how the current economic recession differs from the depressio.pdf
Explain how the current economic recession differs from the depressio.pdf
 
Does yeast uses CopI and CopII formation for vesicle budding to grow.pdf
Does yeast uses CopI and CopII formation for vesicle budding to grow.pdfDoes yeast uses CopI and CopII formation for vesicle budding to grow.pdf
Does yeast uses CopI and CopII formation for vesicle budding to grow.pdf
 
DNA molecules consist of chemically linked sequences of the bases ad.pdf
DNA molecules consist of chemically linked sequences of the bases ad.pdfDNA molecules consist of chemically linked sequences of the bases ad.pdf
DNA molecules consist of chemically linked sequences of the bases ad.pdf
 
Data StructuresPLEASE USING THIS C++ PROGRAM BELOW, I NEED HEL.pdf
Data StructuresPLEASE USING THIS C++ PROGRAM BELOW, I NEED HEL.pdfData StructuresPLEASE USING THIS C++ PROGRAM BELOW, I NEED HEL.pdf
Data StructuresPLEASE USING THIS C++ PROGRAM BELOW, I NEED HEL.pdf
 
apple 2008 historically what were Apples major competitive advanta.pdf
apple 2008 historically what were Apples major competitive advanta.pdfapple 2008 historically what were Apples major competitive advanta.pdf
apple 2008 historically what were Apples major competitive advanta.pdf
 
A partial results from a PERT analysis for a project with 50 activit.pdf
A partial results from a PERT analysis for a project with 50 activit.pdfA partial results from a PERT analysis for a project with 50 activit.pdf
A partial results from a PERT analysis for a project with 50 activit.pdf
 
briefly write about the variability of natural systems and the signi.pdf
briefly write about the variability of natural systems and the signi.pdfbriefly write about the variability of natural systems and the signi.pdf
briefly write about the variability of natural systems and the signi.pdf
 
A graph is symmetric with respect to the vertical line corresponding.pdf
A graph is symmetric with respect to the vertical line corresponding.pdfA graph is symmetric with respect to the vertical line corresponding.pdf
A graph is symmetric with respect to the vertical line corresponding.pdf
 
X-Linked Recessive Write three rules to keep in mind when counseling .pdf
X-Linked Recessive Write three rules to keep in mind when counseling .pdfX-Linked Recessive Write three rules to keep in mind when counseling .pdf
X-Linked Recessive Write three rules to keep in mind when counseling .pdf
 
Write a Java Class to Implement a Generic Linked ListYour list mus.pdf
Write a Java Class to Implement a Generic Linked ListYour list mus.pdfWrite a Java Class to Implement a Generic Linked ListYour list mus.pdf
Write a Java Class to Implement a Generic Linked ListYour list mus.pdf
 
Write a class (BasketballTeam) encapsulating the concept of a tea.pdf
Write a class (BasketballTeam) encapsulating the concept of a tea.pdfWrite a class (BasketballTeam) encapsulating the concept of a tea.pdf
Write a class (BasketballTeam) encapsulating the concept of a tea.pdf
 
Which of the following would you expect to happen in a plant that doe.pdf
Which of the following would you expect to happen in a plant that doe.pdfWhich of the following would you expect to happen in a plant that doe.pdf
Which of the following would you expect to happen in a plant that doe.pdf
 
What is the value of including personal information about yourself a.pdf
What is the value of including personal information about yourself a.pdfWhat is the value of including personal information about yourself a.pdf
What is the value of including personal information about yourself a.pdf
 
What is a voluntary response sampleSolutionVoluntary response.pdf
What is a voluntary response sampleSolutionVoluntary response.pdfWhat is a voluntary response sampleSolutionVoluntary response.pdf
What is a voluntary response sampleSolutionVoluntary response.pdf
 
What adaptive benefit do these abilities give wolbachia In oth.pdf
What adaptive benefit do these abilities give wolbachia In oth.pdfWhat adaptive benefit do these abilities give wolbachia In oth.pdf
What adaptive benefit do these abilities give wolbachia In oth.pdf
 
Think about autumn (Fall season) in places like New England (Pennsyl.pdf
Think about autumn (Fall season) in places like New England (Pennsyl.pdfThink about autumn (Fall season) in places like New England (Pennsyl.pdf
Think about autumn (Fall season) in places like New England (Pennsyl.pdf
 
The orange is which type of fruit Simple - Legume Simple - Drupe .pdf
The orange is which type of fruit  Simple - Legume  Simple - Drupe  .pdfThe orange is which type of fruit  Simple - Legume  Simple - Drupe  .pdf
The orange is which type of fruit Simple - Legume Simple - Drupe .pdf
 
The _________ is the protective chamber that houses the ovule and Lat.pdf
The _________ is the protective chamber that houses the ovule and Lat.pdfThe _________ is the protective chamber that houses the ovule and Lat.pdf
The _________ is the protective chamber that houses the ovule and Lat.pdf
 
Suppose X follows a normal distribution with mean=1 and variance=4. .pdf
Suppose X follows a normal distribution with mean=1 and variance=4. .pdfSuppose X follows a normal distribution with mean=1 and variance=4. .pdf
Suppose X follows a normal distribution with mean=1 and variance=4. .pdf
 

Recently uploaded

Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 

Recently uploaded (20)

Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 

Count Red Nodes. Write a program that computes the percentage of red.pdf

  • 1. Count Red Nodes. Write a program that computes the percentage of red nodes in a given red- black BST. Test your program by running at least 100 trials of the experiment of inserting N random keys into an initially empty tree, for N = 10^4, 10^5, 10^6, and formulate an hypothesis. *It is experiment from textbook Algorithms, 3.3.42 Does anyone know the answer? Solution /* * Java Program to Implement Red Black Tree */ import java.util.Scanner; /* Class Node */ class RedBlackNode { RedBlackNode left, right; int element; int color; /* Constructor */ public RedBlackNode(int theElement) { this( theElement, null, null ); } /* Constructor */ public RedBlackNode(int theElement, RedBlackNode lt, RedBlackNode rt) { left = lt; right = rt; element = theElement; color = 1; } }
  • 2. /* Class RBTree */ class RBTree { private RedBlackNode current; private RedBlackNode parent; private RedBlackNode grand; private RedBlackNode great; private RedBlackNode header; private static RedBlackNode nullNode; /* static initializer for nullNode */ static { nullNode = new RedBlackNode(0); nullNode.left = nullNode; nullNode.right = nullNode; } /* Black - 1 RED - 0 */ static final int BLACK = 1; static final int RED = 0; /* Constructor */ public RBTree(int negInf) { header = new RedBlackNode(negInf); header.left = nullNode; header.right = nullNode; } /* Function to check if tree is empty */ public boolean isEmpty() { return header.right == nullNode; } /* Make the tree logically empty */ public void makeEmpty() {
  • 3. header.right = nullNode; } /* Function to insert item */ public void insert(int item ) { current = parent = grand = header; nullNode.element = item; while (current.element != item) { great = grand; grand = parent; parent = current; current = item < current.element ? current.left : current.right; // Check if two red children and fix if so if (current.left.color == RED && current.right.color == RED) handleReorient( item ); } // Insertion fails if already present if (current != nullNode) return; current = new RedBlackNode(item, nullNode, nullNode); // Attach to parent if (item < parent.element) parent.left = current; else parent.right = current; handleReorient( item ); } private void handleReorient(int item) { // Do the color flip current.color = RED; current.left.color = BLACK; current.right.color = BLACK; if (parent.color == RED)
  • 4. { // Have to rotate grand.color = RED; if (item < grand.element != item < parent.element) parent = rotate( item, grand ); // Start dbl rotate current = rotate(item, great ); current.color = BLACK; } // Make root black header.right.color = BLACK; } private RedBlackNode rotate(int item, RedBlackNode parent) { if(item < parent.element) return parent.left = item < parent.left.element ? rotateWithLeftChild(parent.left) : rotateWithRightChild(parent.left) ; else return parent.right = item < parent.right.element ? rotateWithLeftChild(parent.right) : rotateWithRightChild(parent.right); } /* Rotate binary tree node with left child */ private RedBlackNode rotateWithLeftChild(RedBlackNode k2) { RedBlackNode k1 = k2.left; k2.left = k1.right; k1.right = k2; return k1; } /* Rotate binary tree node with right child */ private RedBlackNode rotateWithRightChild(RedBlackNode k1) { RedBlackNode k2 = k1.right; k1.right = k2.left; k2.left = k1; return k2; }
  • 5. /* Functions to count number of nodes */ public int countNodes() { return countNodes(header.right); } private int countNodes(RedBlackNode r) { if (r == nullNode) 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(header.right, val); } private boolean search(RedBlackNode r, int val) { boolean found = false; while ((r != nullNode) && !found) { int rval = r.element; if (val < rval) r = r.left; else if (val > rval) r = r.right; else { found = true; break;
  • 6. } found = search(r, val); } return found; } /* Function for inorder traversal */ public void inorder() { inorder(header.right); } private void inorder(RedBlackNode r) { if (r != nullNode) { inorder(r.left); char c = 'B'; if (r.color == 0) c = 'R'; System.out.print(r.element +""+c+" "); inorder(r.right); } } /* Function for preorder traversal */ public void preorder() { preorder(header.right); } private void preorder(RedBlackNode r) { if (r != nullNode) { char c = 'B'; if (r.color == 0) c = 'R'; System.out.print(r.element +""+c+" "); preorder(r.left);
  • 7. preorder(r.right); } } /* Function for postorder traversal */ public void postorder() { postorder(header.right); } private void postorder(RedBlackNode r) { if (r != nullNode) { postorder(r.left); postorder(r.right); char c = 'B'; if (r.color == 0) c = 'R'; System.out.print(r.element +""+c+" "); } } } /* Class RedBlackTreeTest */ public class RedBlackTreeTest { public static void main(String[] args) { Scanner scan = new Scanner(System.in); /* Creating object of RedBlack Tree */ RBTree rbt = new RBTree(Integer.MIN_VALUE); System.out.println("Red Black Tree Test "); char ch; /* Perform tree operations */ do { System.out.println(" Red Black Tree Operations ");
  • 8. 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"); rbt.insert( scan.nextInt() ); break; case 2 : System.out.println("Enter integer element to search"); System.out.println("Search result : "+ rbt.search( scan.nextInt() )); break; case 3 : System.out.println("Nodes = "+ rbt.countNodes()); break; case 4 : System.out.println("Empty status = "+ rbt.isEmpty()); break; case 5 : System.out.println(" Tree Cleared"); rbt.makeEmpty(); break; default : System.out.println("Wrong Entry "); break; } /* Display tree */ System.out.print(" Post order : "); rbt.postorder(); System.out.print(" Pre order : "); rbt.preorder();
  • 9. System.out.print(" In order : "); rbt.inorder(); System.out.println(" Do you want to continue (Type y or n) "); ch = scan.next().charAt(0); } while (ch == 'Y'|| ch == 'y'); } } OutPut: