How can a binary tree be determined as a Binary Search Tree (BST)?

  

1. Extend the class BinaryTree to include a boolean method that determines whether a binary tree is a
BST.
ANSWER:
public boolean isBinarySearchTree() {
return isBST(root);
}
//helper method called by isBinarySearchTree
public boolean isBST(BinaryTreeNode tree){

}
2. Extend the class BinaryTree to include a boolean method similarTrees that determines whether the
shapes of two trees are the same (the nodes do not have to contain the same values, but each node must
have the same number of children)
ANSWER:
public boolean similarTrees(BinaryTreeNode otherTree) {
return similar(root, otherTree);
}

//helper method called by similarTrees
public boolean similar(BinaryTreeNode tree1, BinaryTreeNode tree2) {

}
3&4. Extend the class BinaryTree to include 2 more methods: nodeCount (count the number of leaves
in a binary tree) and leavesCount (count the number of nodes in a binary tree). Use recursion in both!
Add statements to the client program (lecture notes) to test these new added methods.
ANSWER:
public int treeLeavesCount() {
return leavesCount(root);
}
//helper method called by treeLeavesCount
private int leavesCount(BinaryTreeNode t) {

}
}
//helper method called by treeNodeCount
private int nodeCount(BinaryTreeNode t) {

}
ADT:BINARYSEARCHTREES
TOPICS
TreesTerminology
ADTBinaryTree:Definitions,JavaImplementation
ADTBinarySearchTree:Definitions,Operations,JavaImplementation
oSearch
oInsertNode
oDeleteNode
OUTLINE
1.TreesTerminology
Datastructureswithcomponentsarrangedinlinearform(uniquefirstcomponentanduniquelastcomponent,everyothercomponenthasauniquepredecessoranda
uniquesuccessor):arrays,lists,stacks,queues.
Datastructureswithcomponentsarrangedinhierarchicalform(hierarchy=nonlinearstructureinwhicheachcomponentmayhaveseveralsuccessors):trees.
Intuitively,hierarchicalmeansthata”parentchild”relationshipexistsbetweenthenodesinthetree.
Hierarchicalformsreallifeexamples:afamilytree,thebiologicalclassificationsystem,businessorganizationcharts(department,division,group,subsidiary),etc.
Definition_Tree=ahierarchicalstructureinwhicheachcomponent,exceptthetopmost,isimmediatelybeneathexactlyoneothercomponent(eachcomponentmay
haveseveralsuccessorsbutonlyonepredecessor).
Definitionsfortermsusedwithgeneraltrees:
oNodes=vertices(treecomponents).Everynode(excepttheroot)hasauniqueparent.Typeofnodes:
Root=starting(topmost)nodeinthetree.Itistheonlynodeinthetreethathasnoparent.
Internalnode=anodewithchildren
Leaf=anodewithoutchildren.Atreemusthaveonlyonerootandmustbranchouttoallleaves.
oEdges=branches(linesbetweenthenodes).Directededgesfromparenttochild.
oParent=Thenodeimmediatelyaboveanothernode
oParenthoodrelationship(ancestoranddescendant):{a,b}anedgebetweennodesaandbandaisabovenodebinthetree>a=parent(ancestor),b=child
(descendant).Theroothasnoparent.Therootofanytreeisanancestorofeverynodeinthattree.
oLeftchild=Thenodetotheleftofanothernodeinatree
oRightchild=Thenodetotherightofanothernodeinatree
oChildrenofthesameparentarecalledsiblings.
oAsubtreeinatreeisanynodeinthetreetogetherwithallofitsdescendants.Asubtreeisatreebyitselfbutisalsopartofalargertree.Recursivedefinition:
1.Theemptytreeisasubtreeofanytree.
2.Anynodeofatree,togetherwithallitsdescendants,isasubtree.
oAsubtreeofanodenisasubtreerootedatachildofn.
oLeftsubtree=Asetofnodestotheleftofanodeinatree
oRightsubtree=Asetofnodestotherightofanodeinatree
oLevel(node)Theleveloftherootisdefinedtobe0,andthelevelofanyothernodeisonemorethanthelevelofitsparent.
oDegree(node)=#ofchildren.
oDegree(tree)=maxdegree(allnodes).
oPath=sequenceofnodesn1,n2,,nksuchthatniistheparentofni+1forall1

Don't use plagiarized sources. Get Your Custom Essay on
How can a binary tree be determined as a Binary Search Tree (BST)?
Just from $13/Page
Order Essay

Introduction:
Binary Trees are data structures that store data in a hierarchical form. They contain nodes arranged in a specific manner that provides a suitable way of searching, sorting, and manipulating data. Binary Search Trees are a subclass of Binary Trees that are organized in a specific way to make searching for elements easier. In this context, we will be exploring different ways to extend the class BinaryTree in Java to add new functionalities.

Description:
Binary Search Trees are useful data structures that allow for quick searching of elements within a tree. The BinaryTree class in Java provides basic functionalities for creating and manipulating binary trees. To extend these functionalities, we can add additional methods to the existing BinaryTree class. One such method is a boolean function that determines whether a binary tree is a BST. This is achieved by implementing the isBST(root) helper function. Additionally, we can add a new boolean function called similarTrees that determines whether two trees have the same shape. These functions help enhance the utility of the BinaryTree class. Furthermore, we can add two more methods to the BinaryTree class called nodeCount and leavesCount. The nodeCount method provides the number of nodes in a binary tree, while the leavesCount method returns the number of leaves in a binary tree. These methods utilize recursion and can be helpful in various tree-related tasks.

Objectives:
1. To understand the concept of binary trees and binary search trees.
2. To extend the class BinaryTree to include additional methods, such as isBinarySearchTree(), similarTrees(), nodeCount(), and leavesCount().
3. To practice using recursion in implementing these methods.

Learning Outcomes:
1. Students will be able to define and explain the terminology used in binary trees, including nodes, edges, parent, child, root, internal node, leaf, subtree, level, degree, and path.
2. Students will be able to implement the isBinarySearchTree() method to determine whether a binary tree is a binary search tree.
3. Students will be able to implement the similarTrees() method to compare the shapes of two binary trees.
4. Students will be able to implement the nodeCount() method to count the number of nodes in a binary tree, and the leavesCount() method to count the number of leaves in a binary tree, using recursion.
5. Students will be able to write client programs to test the new methods added to the BinaryTree class.

Solution 1:
Extend the class BinaryTree to include a boolean method that determines whether a binary tree is a BST. This can be achieved by adding the helper method called isBST which recursively checks if the current node is greater than the left child and smaller than the right child. If both the left and right children are null, then we return true from the function since we have reached the end of the tree. Otherwise, we need to continue checking if the left and right subtrees of the current node are also BSTs by recursively calling the isBST function. The added solution code would look like this:

Solution 1: Extend the class BinaryTree to include a boolean method to determine if a binary tree is BST

public boolean isBinarySearchTree() {
return isBST(root);
}

public boolean isBST(BinaryTreeNode tree){
if(tree == null){
return true;
}
if(tree.getLeftChild() != null && tree.getLeftChild().getData().compareTo(tree.getData()) > 0){
return false;
}
if(tree.getRightChild() != null && tree.getRightChild().getData().compareTo(tree.getData()) < 0){ return false; } return isBST(tree.getLeftChild()) && isBST(tree.getRightChild()); } Solution 2: Extend the class BinaryTree to include a boolean method similarTrees to determine if the shapes of two trees are the same. Here, we will compare the shape of two trees by using recursion. We create a helper function called similar, which checks if the current position in both trees is empty or not. If it is, then we need to check if both nodes are empty, and return true if they are. Otherwise, we check if only one of the nodes is empty, in which case we return false, since the tree shapes are not the same. If neither tree is empty, then we will continue checking if their left and right subtrees also have the same shape by recursively calling the similar function. The added solution code would look like this: Solution 2: Extend the class BinaryTree to include a boolean method similarTrees to determine if the shapes of two trees are the same. public boolean similarTrees(BinaryTreeNode otherTree) {
return similar(root, otherTree);
}

public boolean similar(BinaryTreeNode tree1, BinaryTreeNode tree2) {
if(tree1 ==null && tree2 == null){
return true;
}
if(tree1.getData() == null || tree2.getData() == null){
return false;
}
return similar(tree1.getLeftChild(), tree2.getLeftChild()) &&
similar(tree1.getRightChild(), tree2.getRightChild());
}

Solution 3 and 4:
Extend the class BinaryTree to include two more methods called nodeCount and leavesCount. To count the number of nodes in a binary tree, we will use a recursive approach by checking if a node is null or not. If the node is not null, we will increment the count and continue recursively checking the left and right subtrees. On the other hand, to count the number of leaves in a binary tree, we will check if the node is null, in which case we will return 0, and if both the left and right subtrees are null, then we will increment the count of leaves. We will then continue recursively checking both left and right subtrees.

Here’s the added solution code for Node Count and Leaf Count:

public int treeNodeCount() {
return nodeCount(root);
}

private int nodeCount(BinaryTreeNode t) {
if(t == null) {
return 0;
}
else {
return 1+nodeCount(t.getLeftChild())+nodeCount(t.getRightChild());
}
}

public int treeLeavesCount() {
return leavesCount(root);
}

private int leavesCount(BinaryTreeNode t) {
if(t == null) {
return 0;
}
if(t.getLeftChild() == null && t.getRightChild() == null) {
return 1;
}
else {
return leavesCount(t.getLeftChild()) + leavesCount(t.getRightChild());
}
}

In the client program, we would simply test the added methods like this:

BinaryTree tree = new BinaryTree<>(new BinaryTreeNode<>(1));
tree.getRoot().setLeftChild(new BinaryTreeNode<>(2));
tree.getRoot().setRightChild(new BinaryTreeNode<>(3));
tree.getRoot().getLeftChild().setLeftChild(new BinaryTreeNode<>(4));
tree.getRoot().getLeftChild().setRightChild(new BinaryTreeNode<>(5));

System.out.println(“Node count: ” + tree.treeNodeCount());
System.out.println(“Leaf count: ” + tree.treeLeavesCount());

Suggested Resources/Books:
1. “Data Structures and Algorithms Made Easy: Data Structures and Algorithmic Puzzles” by Narasimha Karumanchi
2. “Structure and Interpretation of Computer Programs” by Harold Abelson and Gerald Jay Sussman
3. “Algorithm Design Manual” by Steven Skiena

Similar Asked Questions:
1. How do you determine if a tree is a binary search tree?
2. Can you compare the shapes of two binary trees?
3. How do you count the number of leaves in a binary tree using recursion?
4. How can recursion be used to count the number of nodes in a binary tree?
5. What is the definition of a binary tree and what operations can be performed on it?

Basic features
  • Free title page and bibliography
  • Unlimited revisions
  • Plagiarism-free guarantee
  • Money-back guarantee
  • 24/7 support
On-demand options
  • Writer’s samples
  • Part-by-part delivery
  • Overnight delivery
  • Copies of used sources
  • Expert Proofreading
Paper format
  • 275 words per page
  • 12 pt Arial/Times New Roman
  • Double line spacing
  • Any citation style (APA, MLA, Chicago/Turabian, Harvard)

Our guarantees

Delivering a high-quality product at a reasonable price is not enough anymore.
That’s why we have developed 5 beneficial guarantees that will make your experience with our service enjoyable, easy, and safe.

Money-back guarantee

You have to be 100% sure of the quality of your product to give a money-back guarantee. This describes us perfectly. Make sure that this guarantee is totally transparent.

Read more

Zero-plagiarism guarantee

Each paper is composed from scratch, according to your instructions. It is then checked by our plagiarism-detection software. There is no gap where plagiarism could squeeze in.

Read more

Free-revision policy

Thanks to our free revisions, there is no way for you to be unsatisfied. We will work on your paper until you are completely happy with the result.

Read more

Privacy policy

Your email is safe, as we store it according to international data protection rules. Your bank details are secure, as we use only reliable payment systems.

Read more

Fair-cooperation guarantee

By sending us your money, you buy the service we provide. Check out our terms and conditions if you prefer business talks to be laid out in official language.

Read more
× How can I help you?