Create boolean methods for BinaryTreeNode class to determine whether the node is
ID: 3773331 • Letter: C
Question
Create boolean methods for BinaryTreeNode class to determine whether the node is a leaf or an internal node.
public class BinaryTreeNode<T>{protected T element;protected BinaryTreeNode<T> left, right;
public BinaryTreeNode( T obj){
element = obj;left = null;right = null;
}
public BinaryTreeNode(T obj, LinkedBinaryTree<T> left, LinkedBinaryTree<T> right){
element = obj;if (left == null)
this.left = null;
else
this.left = left.getRootNode();
if (right == null)
this.right = null;
else
this.right = right.getRootNode();
}
public int numChildren(){
int children = 0;
if (left != null)
children = 1 + left.numChildren();
if (right != null)
children = children + 1 +right.numChildren();
return children;
}
public T getElement(){
return element;}
public BinaryTreeNode<T> getRight(){
return right;
}
public BinaryTreeNode<T> getLeft(){
return left;
}
public void setRight(BinaryTreeNode<T> node){
right = node;
}
public void setLeft(BinaryTreeNode<T> node){
left = node;
}
}
Explanation / Answer
public class LinkedBinaryTree<T> implements BinaryTreeADT<T>, Iterable<T>
{
protected BinaryTreeNode<T> root;
protected int modCount;
public LinkedBinaryTree()
{
root = null;
}
public LinkedBinaryTree(T element)
{
root = new BinaryTreeNode<T>(element);
}
public LinkedBinaryTree(T element, LinkedBinaryTree<T> left,
LinkedBinaryTree<T> right)
{
root = new BinaryTreeNode<T>(element);
root.setLeft(left.root);
root.setRight(right.root);
}
public T getRootElement() throws EmptyCollectionException
{
return root.getElement();
}
protected BinaryTreeNode<T> getRootNode() throws EmptyCollectionException
{
return root;
}
public LinkedBinaryTree<T> getLeft()
{
return root.getLeft();
}
public LinkedBinaryTree<T> getRight()
{
return root.getRight();
}
public boolean isEmpty()
{
return (root == null);
}
Node Class
public class BinaryTreeNode<T>{protected T element;protected BinaryTreeNode<T> left, right;
public BinaryTreeNode( T obj){
element = obj;left = null;right = null;
}
public BinaryTreeNode(T obj, LinkedBinaryTree<T> left, LinkedBinaryTree<T> right){
element = obj;if (left == null)
this.left = null;
else
this.left = left.getRootNode();
if (right == null)
this.right = null;
else
this.right = right.getRootNode();
}
public int numChildren(){
int children = 0;
if (left != null)
children = 1 + left.numChildren();
if (right != null)
children = children + 1 +right.numChildren();
return children;
}
public T getElement(){
return element;}
public BinaryTreeNode<T> getRight(){
return right;
}
public BinaryTreeNode<T> getLeft(){
return left;
}
public void setRight(BinaryTreeNode<T> node){
right = node;
}
public void setLeft(BinaryTreeNode<T> node){
left = node;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.