SlideShare a Scribd company logo
1 of 4
Download to read offline
Binary Tree in Java
Thisis a program of a binary tree which is extended from its super
class SimpleTree. It uses all the functionalities from its super
class. A binary tree consists of two leaves mainly left child nodes
and right child nodes.
There are different methods defined performing different
functionalities. Initially it is checked whether the root node is
created for a binary tree or not. Another method is counting for the
leaves of the binary tree, by counting the left and right child nodes.
Some method is checking for the nodes having both the child nodes
available or not. Also methods are modifying and removing the required
nodes.
public class BinaryTree extends SimpleTree {
// counting leaves
public int countLeaves() {
if (root == null) {
return 0;
} else {
return countLeaves(root);
}
}
/*
* determine how many leaves are in the subtree whose root is
node
* Precondition: node is not null
*/
private int countLeaves(Node n) {
BinaryNode node = (BinaryNode) n;
if ((node.getLeft()==null) && (node.getRight()==null)) {
return 1;
} else if ((node.getLeft()==null) &&
(node.getRight()!=null)) {
return countLeaves(node.getRight());
} else if ((node.getLeft()!=null) &&
(node.getRight()==null)) {
return countLeaves(node.getLeft());
} else {
// this is done when
// ((node.getLeft()!=null) && (node.getRight()!=null))
return countLeaves(node.getLeft()) +
countLeaves(node.getRight());
}
}
// count nodes
/**
* return true when every node in the tree has either two children
or none
* (but no node has only one child)
*/
public boolean twoChildrenOrNone() {
if (root == null) {
return true;
} else {
return twoChildrenOrNone(root);
}
}
/*
* determine whether all the node has two children or none
* Precondition: node is not null
*/
private boolean twoChildrenOrNone(Node n) {
BinaryNode node = (BinaryNode) n;
if ((node.getLeft()==null) && (node.getRight()==null)) {
return true;
} else if ((node.getLeft()==null) &&
(node.getRight()!=null)) {
return false;
} else if ((node.getLeft()!=null) &&
(node.getRight()==null)) {
return false;
} else {
// this is done when
// ((node.getLeft()!=null) && (node.getRight()!=null))
return twoChildrenOrNone(node.getLeft()) &&
twoChildrenOrNone(node.getRight());
}
}
// remove leaves
/**
* modify the tree by removing every leaf node
*/
public void trim() {
if (root != null) {
root = trim(root);
}
}
/*
* remove all the leaves.
* Precondition: node is not null
*/
private BinaryNode trim(Node n) {
BinaryNode node = (BinaryNode) n;
if ((node.getLeft()==null) && (node.getRight()==null)) {
// this is a leaf, remove it from the tree.
return null;
} else if ((node.getLeft()==null) &&
(node.getRight()!=null)) {
node.setRight(trim(node.getRight()));
} else if ((node.getLeft()!=null) &&
(node.getRight()==null)) {
node.setLeft(trim(node.getLeft()));
} else {
// this is done when
// ((node.getLeft()!=null) && (node.getRight()!=null))
node.setLeft(trim(node.getLeft()));
node.setRight(trim(node.getRight()));
}
return node;
}
}

More Related Content

What's hot

13. dynamic allocation
13. dynamic allocation13. dynamic allocation
13. dynamic allocation
웅식 전
 
Listing for TryLambdaExpressions
Listing for TryLambdaExpressionsListing for TryLambdaExpressions
Listing for TryLambdaExpressions
Derek Dhammaloka
 

What's hot (20)

Road to react hooks
Road to react hooksRoad to react hooks
Road to react hooks
 
C SQLite usage
C SQLite usageC SQLite usage
C SQLite usage
 
How to implement joins in mongo db
How to implement joins in mongo dbHow to implement joins in mongo db
How to implement joins in mongo db
 
13. dynamic allocation
13. dynamic allocation13. dynamic allocation
13. dynamic allocation
 
_Function Builders in Swift #love_swift
_Function Builders in Swift #love_swift_Function Builders in Swift #love_swift
_Function Builders in Swift #love_swift
 
Constructors
ConstructorsConstructors
Constructors
 
Connectivity coding for java and mysql
Connectivity coding for java and mysqlConnectivity coding for java and mysql
Connectivity coding for java and mysql
 
ORM is offensive
ORM is offensiveORM is offensive
ORM is offensive
 
Backups with Exported Resources - Zach Leslie, Puppet Labs
Backups with Exported Resources - Zach Leslie, Puppet Labs Backups with Exported Resources - Zach Leslie, Puppet Labs
Backups with Exported Resources - Zach Leslie, Puppet Labs
 
constructor and destructor
constructor and destructorconstructor and destructor
constructor and destructor
 
Listing for TryLambdaExpressions
Listing for TryLambdaExpressionsListing for TryLambdaExpressions
Listing for TryLambdaExpressions
 
Litebox
LiteboxLitebox
Litebox
 
AngularJs
AngularJsAngularJs
AngularJs
 
Redis the better NoSQL
Redis the better NoSQLRedis the better NoSQL
Redis the better NoSQL
 
React, Redux, ES2015 by Max Petruck
React, Redux, ES2015 by Max PetruckReact, Redux, ES2015 by Max Petruck
React, Redux, ES2015 by Max Petruck
 
supporting t-sql scripts for IndexPage, Datapage and IndexDefragmentation
supporting t-sql scripts for IndexPage, Datapage and IndexDefragmentationsupporting t-sql scripts for IndexPage, Datapage and IndexDefragmentation
supporting t-sql scripts for IndexPage, Datapage and IndexDefragmentation
 
How Much Immutability Is Enough?
How Much Immutability Is Enough?How Much Immutability Is Enough?
How Much Immutability Is Enough?
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
MySql:Introduction
MySql:IntroductionMySql:Introduction
MySql:Introduction
 
Riak Search 2: Yokozuna
Riak Search 2: YokozunaRiak Search 2: Yokozuna
Riak Search 2: Yokozuna
 

Viewers also liked (8)

Expression tree
Expression treeExpression tree
Expression tree
 
vim
vimvim
vim
 
Expression trees
Expression treesExpression trees
Expression trees
 
Computer notes - Expression Tree
Computer notes - Expression TreeComputer notes - Expression Tree
Computer notes - Expression Tree
 
Implementation of trees
Implementation of trees Implementation of trees
Implementation of trees
 
Infix to Prefix (Conversion, Evaluation, Code)
Infix to Prefix (Conversion, Evaluation, Code)Infix to Prefix (Conversion, Evaluation, Code)
Infix to Prefix (Conversion, Evaluation, Code)
 
1.4 expression tree
1.4 expression tree  1.4 expression tree
1.4 expression tree
 
flag of india ppt
flag of india pptflag of india ppt
flag of india ppt
 

Similar to Binary tree in java

Once you have all the structures working as intended- it is time to co.docx
Once you have all the structures working as intended- it is time to co.docxOnce you have all the structures working as intended- it is time to co.docx
Once you have all the structures working as intended- it is time to co.docx
farrahkur54
 
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
 
Please write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdfPlease write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdf
ajaycosmeticslg
 
Add these three functions to the class binaryTreeType (provided).W.pdf
Add these three functions to the class binaryTreeType (provided).W.pdfAdd these three functions to the class binaryTreeType (provided).W.pdf
Add these three functions to the class binaryTreeType (provided).W.pdf
indiaartz
 
Decision tree handson
Decision tree handsonDecision tree handson
Decision tree handson
Shyam Sarkar
 
Need Help with this Java Assignment. Program should be done in JAVA .pdf
Need Help with this Java Assignment. Program should be done in JAVA .pdfNeed Help with this Java Assignment. Program should be done in JAVA .pdf
Need Help with this Java Assignment. Program should be done in JAVA .pdf
archiesgallery
 
Create an implementation of a binary tree using the recursive appr.pdf
Create an implementation of a binary tree using the recursive appr.pdfCreate an implementation of a binary tree using the recursive appr.pdf
Create an implementation of a binary tree using the recursive appr.pdf
federaleyecare
 
include ltiostreamgt include ltfstreamgt in.pdf
include ltiostreamgt include ltfstreamgt in.pdfinclude ltiostreamgt include ltfstreamgt in.pdf
include ltiostreamgt include ltfstreamgt in.pdf
adisainternational
 
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
 
Please i need help on following program using C++ Language.Add the.pdf
Please i need help on following program using C++ Language.Add the.pdfPlease i need help on following program using C++ Language.Add the.pdf
Please i need help on following program using C++ Language.Add the.pdf
ezzi552
 
A)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdfA)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdf
anton291
 
4. The size of instructions can be fixed or variable. What are advant.pdf
4. The size of instructions can be fixed or variable. What are advant.pdf4. The size of instructions can be fixed or variable. What are advant.pdf
4. The size of instructions can be fixed or variable. What are advant.pdf
mumnesh
 
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
 
Given a newly created Binary Search Tree with the following numerica.pdf
Given a newly created Binary Search Tree with the following numerica.pdfGiven a newly created Binary Search Tree with the following numerica.pdf
Given a newly created Binary Search Tree with the following numerica.pdf
hadpadrrajeshh
 
create a binary search tree from an empty one by adding the key valu.pdf
create a binary search tree from an empty one by adding the key valu.pdfcreate a binary search tree from an empty one by adding the key valu.pdf
create a binary search tree from an empty one by adding the key valu.pdf
erremmfab
 
hi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdfhi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdf
archgeetsenterprises
 
main.cpp#include TreeNode.h GIVEN void inorderTraversal(.pdf
main.cpp#include TreeNode.h GIVEN void inorderTraversal(.pdfmain.cpp#include TreeNode.h GIVEN void inorderTraversal(.pdf
main.cpp#include TreeNode.h GIVEN void inorderTraversal(.pdf
pratikradia365
 
For this project, write a program that stores integers in a binary.docx
For this project, write a program that stores integers in a binary.docxFor this project, write a program that stores integers in a binary.docx
For this project, write a program that stores integers in a binary.docx
budbarber38650
 

Similar to Binary tree in java (20)

Once you have all the structures working as intended- it is time to co.docx
Once you have all the structures working as intended- it is time to co.docxOnce you have all the structures working as intended- it is time to co.docx
Once you have all the structures working as intended- it is time to co.docx
 
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
 
Please write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdfPlease write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdf
 
Add these three functions to the class binaryTreeType (provided).W.pdf
Add these three functions to the class binaryTreeType (provided).W.pdfAdd these three functions to the class binaryTreeType (provided).W.pdf
Add these three functions to the class binaryTreeType (provided).W.pdf
 
Decision tree handson
Decision tree handsonDecision tree handson
Decision tree handson
 
Need Help with this Java Assignment. Program should be done in JAVA .pdf
Need Help with this Java Assignment. Program should be done in JAVA .pdfNeed Help with this Java Assignment. Program should be done in JAVA .pdf
Need Help with this Java Assignment. Program should be done in JAVA .pdf
 
Using the following definition for a Binary Tree Node - complete the f.docx
Using the following definition for a Binary Tree Node - complete the f.docxUsing the following definition for a Binary Tree Node - complete the f.docx
Using the following definition for a Binary Tree Node - complete the f.docx
 
Create an implementation of a binary tree using the recursive appr.pdf
Create an implementation of a binary tree using the recursive appr.pdfCreate an implementation of a binary tree using the recursive appr.pdf
Create an implementation of a binary tree using the recursive appr.pdf
 
include ltiostreamgt include ltfstreamgt in.pdf
include ltiostreamgt include ltfstreamgt in.pdfinclude ltiostreamgt include ltfstreamgt in.pdf
include ltiostreamgt include ltfstreamgt in.pdf
 
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
 
Please i need help on following program using C++ Language.Add the.pdf
Please i need help on following program using C++ Language.Add the.pdfPlease i need help on following program using C++ Language.Add the.pdf
Please i need help on following program using C++ Language.Add the.pdf
 
A)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdfA)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdf
 
4. The size of instructions can be fixed or variable. What are advant.pdf
4. The size of instructions can be fixed or variable. What are advant.pdf4. The size of instructions can be fixed or variable. What are advant.pdf
4. The size of instructions can be fixed or variable. What are advant.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
 
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
 
Given a newly created Binary Search Tree with the following numerica.pdf
Given a newly created Binary Search Tree with the following numerica.pdfGiven a newly created Binary Search Tree with the following numerica.pdf
Given a newly created Binary Search Tree with the following numerica.pdf
 
create a binary search tree from an empty one by adding the key valu.pdf
create a binary search tree from an empty one by adding the key valu.pdfcreate a binary search tree from an empty one by adding the key valu.pdf
create a binary search tree from an empty one by adding the key valu.pdf
 
hi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdfhi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdf
 
main.cpp#include TreeNode.h GIVEN void inorderTraversal(.pdf
main.cpp#include TreeNode.h GIVEN void inorderTraversal(.pdfmain.cpp#include TreeNode.h GIVEN void inorderTraversal(.pdf
main.cpp#include TreeNode.h GIVEN void inorderTraversal(.pdf
 
For this project, write a program that stores integers in a binary.docx
For this project, write a program that stores integers in a binary.docxFor this project, write a program that stores integers in a binary.docx
For this project, write a program that stores integers in a binary.docx
 

More from Programming Homework Help

More from Programming Homework Help (8)

Java Assignment Help
Java  Assignment  HelpJava  Assignment  Help
Java Assignment Help
 
C# Assignmet Help
C# Assignmet HelpC# Assignmet Help
C# Assignmet Help
 
C# Assignmet Help
C# Assignmet HelpC# Assignmet Help
C# Assignmet Help
 
Family tree in java
Family tree in javaFamily tree in java
Family tree in java
 
Bank account in java
Bank account in javaBank account in java
Bank account in java
 
Mouse and Cat Game In C++
Mouse and Cat Game In C++Mouse and Cat Game In C++
Mouse and Cat Game In C++
 
Word games in c
Word games in cWord games in c
Word games in c
 
Card Games in C++
Card Games in C++Card Games in C++
Card Games in C++
 

Recently uploaded

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

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
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
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
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
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...
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
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
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
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Ữ Â...
 

Binary tree in java

  • 1.
  • 2. Binary Tree in Java Thisis a program of a binary tree which is extended from its super class SimpleTree. It uses all the functionalities from its super class. A binary tree consists of two leaves mainly left child nodes and right child nodes. There are different methods defined performing different functionalities. Initially it is checked whether the root node is created for a binary tree or not. Another method is counting for the leaves of the binary tree, by counting the left and right child nodes. Some method is checking for the nodes having both the child nodes available or not. Also methods are modifying and removing the required nodes. public class BinaryTree extends SimpleTree { // counting leaves public int countLeaves() { if (root == null) { return 0; } else { return countLeaves(root); } } /* * determine how many leaves are in the subtree whose root is node * Precondition: node is not null */ private int countLeaves(Node n) { BinaryNode node = (BinaryNode) n; if ((node.getLeft()==null) && (node.getRight()==null)) { return 1; } else if ((node.getLeft()==null) && (node.getRight()!=null)) { return countLeaves(node.getRight()); } else if ((node.getLeft()!=null) && (node.getRight()==null)) { return countLeaves(node.getLeft()); } else { // this is done when // ((node.getLeft()!=null) && (node.getRight()!=null)) return countLeaves(node.getLeft()) + countLeaves(node.getRight()); } } // count nodes
  • 3. /** * return true when every node in the tree has either two children or none * (but no node has only one child) */ public boolean twoChildrenOrNone() { if (root == null) { return true; } else { return twoChildrenOrNone(root); } } /* * determine whether all the node has two children or none * Precondition: node is not null */ private boolean twoChildrenOrNone(Node n) { BinaryNode node = (BinaryNode) n; if ((node.getLeft()==null) && (node.getRight()==null)) { return true; } else if ((node.getLeft()==null) && (node.getRight()!=null)) { return false; } else if ((node.getLeft()!=null) && (node.getRight()==null)) { return false; } else { // this is done when // ((node.getLeft()!=null) && (node.getRight()!=null)) return twoChildrenOrNone(node.getLeft()) && twoChildrenOrNone(node.getRight()); } } // remove leaves /** * modify the tree by removing every leaf node */ public void trim() { if (root != null) { root = trim(root); } } /* * remove all the leaves. * Precondition: node is not null */ private BinaryNode trim(Node n) { BinaryNode node = (BinaryNode) n; if ((node.getLeft()==null) && (node.getRight()==null)) {
  • 4. // this is a leaf, remove it from the tree. return null; } else if ((node.getLeft()==null) && (node.getRight()!=null)) { node.setRight(trim(node.getRight())); } else if ((node.getLeft()!=null) && (node.getRight()==null)) { node.setLeft(trim(node.getLeft())); } else { // this is done when // ((node.getLeft()!=null) && (node.getRight()!=null)) node.setLeft(trim(node.getLeft())); node.setRight(trim(node.getRight())); } return node; } }