Menu

[solved]-Way Improve Program Add Something Make Similar Also Please Show Binary Tree Mark Authors Q39035473

Is there any way I can improve this program such as addsomething to it to make it similar. Also please show me how.

// Binary Tree
// Mark
// Authors
// Implements a binary tree

public class BinaryTree<E extends Comparable<E>>{
// Instance variables
private BinaryTreeNode<E> root;

// Constructor
public BinaryTree() {
clear();
}

// Instance Methods

// Returns whether tree is empty
public boolean isEmpty() {
return root == null;
}

// Empties the tree
public void clear() {
root = null;
}

// Insert node into a binary tree including the empty treecase.
public void insertInBinaryTree(E newItem) {
if (isEmpty()) {
root = new BinaryTreeNode<E>(newItem);
} else {
insert(root, newItem);
}
}

// Insert in non-empty tree. Used by insertInBinaryTree
private void insert(BinaryTreeNode<E> treeNode, E newItem){
if (newItem.compareTo(treeNode.getItem()) < 0) {
// Insert in left subtree
if (treeNode.getLeftChild() == null) {
// No left child. Insert new node.
treeNode.setLeftChild(new BinaryTreeNode<E>(newItem));
} else {
// Left child exists. Call insert in left subtree.
insert(treeNode.getLeftChild(), newItem);
}
} else {
// Insert in right subtree
if (treeNode.getRightChild() == null) {
// No right child. Insert new node.
treeNode.setRightChild(new BinaryTreeNode<E>(newItem));
} else {
// Right child exists. Call insert in left subtree.
insert(treeNode.getRightChild(), newItem);
}
}
}

// Convert the tree to an array
public E[] copyToArray(E[] array) {
fillArray(root, array, 0);

return array;
}

// Recursively fill an array by performing an inorder traversalof the tree
private int fillArray(BinaryTreeNode<E> treeNode, E[] array,int index) {
// This method must perform an inorder traversal (see example fromtext) with
// several changes. Keep the following in mind when writingit:
// – Instead of visiting an node, it copies that node’s value tothe array
// – It always returns the index of the next empty space in thearray
if(treeNode == null)
return -1;
int indx = fillArray(treeNode.getLeftChild(), array, index);
  
if(indx == -1)
indx = index;
array[indx] = treeNode.getItem();
  
int indxr = fillArray(treeNode.getRightChild(), array,indx+1);
if(indxr == -1)
indxr = indx+1;
  
return indxr;
}

// Uses a BinaryTree to sort an array
public static <E extends Comparable<E>> void sort(E[]array) {
// Create a new BinaryTree and add the contents of the array to thetree
BinaryTree<E> tree = new BinaryTree();

for(E element : array)
tree.insertInBinaryTree(element);
// Use the tree to overwrite the array with the elements in sortedorder
tree.copyToArray(array);
}
}

Expert Answer


Answer to Is there any way I can improve this program such as add something to it to make it similar. Also please show me how. // … . . .

OR


Leave a Reply

Your email address will not be published. Required fields are marked *