SlideShare a Scribd company logo
Binary tree in java
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 (20)

PDF
Road to react hooks
Younes (omar) Meliani
 
PDF
C SQLite usage
Chien-Wei Huang
 
DOCX
How to implement joins in mongo db
Prasoon Sharma
 
PDF
13. dynamic allocation
웅식 전
 
PDF
_Function Builders in Swift #love_swift
Tomohiro Kumagai
 
PPTX
Constructors
shravani2191
 
DOCX
Connectivity coding for java and mysql
Fahad Ali Khan
 
PDF
ORM is offensive
Yegor Bugayenko
 
PDF
Backups with Exported Resources - Zach Leslie, Puppet Labs
Puppet
 
PPTX
constructor and destructor
VENNILAV6
 
PDF
Listing for TryLambdaExpressions
Derek Dhammaloka
 
TXT
Litebox
meli media
 
PDF
AngularJs
Hossein Baghayi
 
PDF
Redis the better NoSQL
OpenFest team
 
PDF
React, Redux, ES2015 by Max Petruck
Lingvokot
 
DOCX
supporting t-sql scripts for IndexPage, Datapage and IndexDefragmentation
Mahabubur Rahaman
 
PDF
How Much Immutability Is Enough?
Yegor Bugayenko
 
PPTX
Constructor ppt
Vinod Kumar
 
PPTX
MySql:Introduction
DataminingTools Inc
 
PDF
Riak Search 2: Yokozuna
PDX Web & Design
 
Road to react hooks
Younes (omar) Meliani
 
C SQLite usage
Chien-Wei Huang
 
How to implement joins in mongo db
Prasoon Sharma
 
13. dynamic allocation
웅식 전
 
_Function Builders in Swift #love_swift
Tomohiro Kumagai
 
Constructors
shravani2191
 
Connectivity coding for java and mysql
Fahad Ali Khan
 
ORM is offensive
Yegor Bugayenko
 
Backups with Exported Resources - Zach Leslie, Puppet Labs
Puppet
 
constructor and destructor
VENNILAV6
 
Listing for TryLambdaExpressions
Derek Dhammaloka
 
Litebox
meli media
 
AngularJs
Hossein Baghayi
 
Redis the better NoSQL
OpenFest team
 
React, Redux, ES2015 by Max Petruck
Lingvokot
 
supporting t-sql scripts for IndexPage, Datapage and IndexDefragmentation
Mahabubur Rahaman
 
How Much Immutability Is Enough?
Yegor Bugayenko
 
Constructor ppt
Vinod Kumar
 
MySql:Introduction
DataminingTools Inc
 
Riak Search 2: Yokozuna
PDX Web & Design
 

Viewers also liked (8)

PPTX
Expression tree
LearningTech
 
PPTX
vim
LearningTech
 
PDF
Expression trees
Salman Vadsarya
 
PPT
Computer notes - Expression Tree
ecomputernotes
 
PPTX
Implementation of trees
Mubashar Mehmood
 
PDF
Infix to Prefix (Conversion, Evaluation, Code)
Ahmed Khateeb
 
PPT
1.4 expression tree
Krish_ver2
 
PPT
flag of india ppt
Sanjay Patange
 
Expression tree
LearningTech
 
Expression trees
Salman Vadsarya
 
Computer notes - Expression Tree
ecomputernotes
 
Implementation of trees
Mubashar Mehmood
 
Infix to Prefix (Conversion, Evaluation, Code)
Ahmed Khateeb
 
1.4 expression tree
Krish_ver2
 
flag of india ppt
Sanjay Patange
 
Ad

Similar to Binary tree in java (20)

PDF
A perfect left-sided binary tree is a binary tree where every intern.pdf
michardsonkhaicarr37
 
DOCX
Once you have all the structures working as intended- it is time to co.docx
farrahkur54
 
PDF
How to do the main method for this programBinaryNode.javapublic.pdf
feelingcomputors
 
PDF
Given BinaryNode.javapackage util;import java.util.;T.pdf
Conint29
 
PDF
Create an implementation of a binary tree using the recursive appr.pdf
federaleyecare
 
PDF
On the code which has a class in which I implementing a binary tree .pdf
wasemanivytreenrco51
 
DOCX
For this project, write a program that stores integers in a binary.docx
budbarber38650
 
PDF
I have a .java program that I need to modify so that it1) reads i.pdf
allystraders
 
DOCX
Decision tree handson
Shyam Sarkar
 
PDF
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Footageetoffe16
 
PDF
For the code below complete the preOrder() method so that it perform.pdf
xlynettalampleyxc
 
DOCX
Required to augment the authors Binary Search Tree (BST) code to .docx
debishakespeare
 
PDF
import javautilQueue import javautilLinkedList import .pdf
ADITIEYEWEAR
 
PDF
import java.util.Scanner;class BinaryNode{     BinaryNode left.pdf
shaktisinhgandhinaga
 
PDF
To create a node for a binary search tree (BTNode, ) and to create a .pdf
bhim1213
 
PDF
Given the following codepackage data1;import java.util.;p.pdf
illyasraja7
 
PDF
1)(JAVA) Extend the Binary Search Tree ADT to include a public metho.pdf
petercoiffeur18
 
PDF
package DataStructures; public class HelloWorld AnyType extends.pdf
apleathers
 
PDF
Need Help with this Java Assignment. Program should be done in JAVA .pdf
archiesgallery
 
PDF
JavaCreate a java application using the code example in the follo.pdf
ambersushil
 
A perfect left-sided binary tree is a binary tree where every intern.pdf
michardsonkhaicarr37
 
Once you have all the structures working as intended- it is time to co.docx
farrahkur54
 
How to do the main method for this programBinaryNode.javapublic.pdf
feelingcomputors
 
Given BinaryNode.javapackage util;import java.util.;T.pdf
Conint29
 
Create an implementation of a binary tree using the recursive appr.pdf
federaleyecare
 
On the code which has a class in which I implementing a binary tree .pdf
wasemanivytreenrco51
 
For this project, write a program that stores integers in a binary.docx
budbarber38650
 
I have a .java program that I need to modify so that it1) reads i.pdf
allystraders
 
Decision tree handson
Shyam Sarkar
 
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Footageetoffe16
 
For the code below complete the preOrder() method so that it perform.pdf
xlynettalampleyxc
 
Required to augment the authors Binary Search Tree (BST) code to .docx
debishakespeare
 
import javautilQueue import javautilLinkedList import .pdf
ADITIEYEWEAR
 
import java.util.Scanner;class BinaryNode{     BinaryNode left.pdf
shaktisinhgandhinaga
 
To create a node for a binary search tree (BTNode, ) and to create a .pdf
bhim1213
 
Given the following codepackage data1;import java.util.;p.pdf
illyasraja7
 
1)(JAVA) Extend the Binary Search Tree ADT to include a public metho.pdf
petercoiffeur18
 
package DataStructures; public class HelloWorld AnyType extends.pdf
apleathers
 
Need Help with this Java Assignment. Program should be done in JAVA .pdf
archiesgallery
 
JavaCreate a java application using the code example in the follo.pdf
ambersushil
 
Ad

More from Programming Homework Help (8)

PDF
Java Assignment Help
Programming Homework Help
 
PDF
C# Assignmet Help
Programming Homework Help
 
PDF
C# Assignmet Help
Programming Homework Help
 
PDF
Family tree in java
Programming Homework Help
 
PDF
Bank account in java
Programming Homework Help
 
PDF
Mouse and Cat Game In C++
Programming Homework Help
 
PDF
Word games in c
Programming Homework Help
 
PDF
Card Games in C++
Programming Homework Help
 
Java Assignment Help
Programming Homework Help
 
C# Assignmet Help
Programming Homework Help
 
C# Assignmet Help
Programming Homework Help
 
Family tree in java
Programming Homework Help
 
Bank account in java
Programming Homework Help
 
Mouse and Cat Game In C++
Programming Homework Help
 
Word games in c
Programming Homework Help
 
Card Games in C++
Programming Homework Help
 

Recently uploaded (20)

PDF
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
PPTX
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
PDF
People & Earth's Ecosystem -Lesson 2: People & Population
marvinnbustamante1
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PPTX
Mathematics 5 - Time Measurement: Time Zone
menchreo
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PDF
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PDF
community health nursing question paper 2.pdf
Prince kumar
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PPTX
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PPTX
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPTX
THE TAME BIRD AND THE FREE BIRD.pptxxxxx
MarcChristianNicolas
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PPTX
How to Set Maximum Difference Odoo 18 POS
Celine George
 
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
People & Earth's Ecosystem -Lesson 2: People & Population
marvinnbustamante1
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
Mathematics 5 - Time Measurement: Time Zone
menchreo
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
community health nursing question paper 2.pdf
Prince kumar
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
THE TAME BIRD AND THE FREE BIRD.pptxxxxx
MarcChristianNicolas
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
Dimensions of Societal Planning in Commonism
StefanMz
 
How to Set Maximum Difference Odoo 18 POS
Celine George
 

Binary tree in java

  • 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; } }