SlideShare a Scribd company logo
1 of 9
Download to read offline
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 

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

QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
httgc7rh9c
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
EADTU
 

Recently uploaded (20)

Introduction to TechSoup’s Digital Marketing Services and Use Cases
Introduction to TechSoup’s Digital Marketing  Services and Use CasesIntroduction to TechSoup’s Digital Marketing  Services and Use Cases
Introduction to TechSoup’s Digital Marketing Services and Use Cases
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learning
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
 
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdfUGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Michaelis Menten Equation and Estimation Of Vmax and Tmax.pptx
Michaelis Menten Equation and Estimation Of Vmax and Tmax.pptxMichaelis Menten Equation and Estimation Of Vmax and Tmax.pptx
Michaelis Menten Equation and Estimation Of Vmax and Tmax.pptx
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
PANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxPANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptx
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of Play
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdf
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
 

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: