Inserting an integer into a regular binary tree - java

While revising for my final, I came across binary trees (regular ones). After going through the lecture, I started to solve previous labs.
My problem here is that only 6 is inserted into the tree. What is wrong with my method?
What I'm trying to input:
tree.insert(1); tree.insert(15); tree.insert(7);
tree.insert(13); tree.insert(58); tree.insert(6);
The Node class:
public class Node {
public int key;
public Node left_child;
public Node right_child;
// The Constructor(s).
public Node() {
}
public Node(int key) {
this.key = key;
left_child = null;
right_child = null;
}
// The Get Methods.
public int getKey() {
return key;
}
public Node getLeft_child() {
return left_child;
}
public Node getRight_child() {
return right_child;
}
// The Set Methods.
public void setKey(int key) {
this.key = key;
}
public void setLeft_child(Node left_child) {
this.left_child = left_child;
}
public void setRight_child(Node right_child) {
this.right_child = right_child;
}
}
The BinaryTree class:
public class BinaryTree {
private Node root;
// The Constructor Method(s)
public BinaryTree() {
root = null;
}
public boolean is_empty() {
return (root == null);
}
public void insert(int k) {
insert(root, k);
}
private Node insert(Node x, int k) {
Node p = new Node(k);
if (x == null) {
root = p;
}
else {
if (x.left_child != null) {
insert(x.left_child, k);
}
else {
insert(x.right_child, k);
}
}
return x;
}
// Printing Method(s).
public void print_inorder() {
print_inorder(root);
}
public void print_inorder(Node node) {
if (node == null) {
return;
}
print_inorder(node.left_child);
System.out.print(node.key + " ");
print_inorder(node.right_child);
}
public void print_preorder() {
print_preorder(root);
}
public void print_preorder(Node node) {
if (node == null) {
return;
}
System.out.print(node.key + " ");
print_preorder(node.left_child);
print_preorder(node.right_child);
}
public void print_postorder() {
print_postorder(root);
}
public void print_postorder(Node node) {
if (node == null) {
return;
}
print_postorder(node.left_child);
print_postorder(node.right_child);
System.out.print(node.key + " ");
}
}

This will have a node to the left if a number is even and a node to the right if a node is odd.
I had to change your if condition because the way it was it was never going to use the left node.
private void insert(Node x, int k) {
Node p = new Node(k);
if (root == null) {
this.root = p;
return;
}
if (x.getKey() - k % 2 == 0) {
if (x.left_child == null) {
x.left_child = p;
} else {
insert(x.left_child, k);
}
} else {
if (x.right_child == null) {
x.right_child = p;
} else {
insert(x.right_child, k);
}
}
}

Related

Binary trees to find a dance partner

I wrote the code, but the tests are falling. I can't find what I'm doing wrong.
For example:
FAILURE: testRunOutOfPartnersThenFindSomeMore
2 msecs, weight: 0 units
Description: This tests whether your tree can get empty and then filled again.
Exception type: class java.lang.NullPointerException
FAILURE: testFemaleTreeImplementation
5 msecs, weight: 0 units
Description: This tests, whether your tree works correctly.
Exception type: class java.lang.AssertionError
Detailed information: Your implementation found a pair when it should not have.
Dancer.java
public interface Dancer {
public enum Gender {
MALE, FEMALE
}
public int getID();
public Gender getGender();
public int getHeight();
}
Dancers.java
import java.util.AbstractMap.SimpleEntry;
import java.util.List;
public interface Dancers {
public SimpleEntry<Dancer, Dancer> findPartnerFor(Dancer d) throws IllegalArgumentException;
/*
* Returns waiting list as a list (both men and women)
* Ordered shortest --> longest
* If man and woman are having the same height,
* then ordering should be woman, man
*/
public List<Dancer> returnWaitingList();
}
HW01.java
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.List;
public class HW01 implements Dancers {
public SearchTree maleTree;
public SearchTree femaleTree;
public void createTree(SearchTreeNode n) {
if (n.getKey().getGender().equals(Dancer.Gender.MALE)) {
this.maleTree = new SearchTree(n);
} else {
this.femaleTree = new SearchTree(n);
}
}
#Override
public SimpleEntry<Dancer, Dancer> findPartnerFor(Dancer candidate) throws IllegalArgumentException {
if (candidate == null) throw new IllegalArgumentException();
if (candidate.getGender().equals(Dancer.Gender.MALE)) {
if (this.femaleTree != null) {
// If no match, add to opposite tree
SearchTreeNode match = this.femaleTree.match(candidate);
if (match != null) {
// Remove node from tree
this.femaleTree.delete(match);
return new SimpleEntry<>( candidate, match.getKey() );
} else {
if (this.maleTree != null) {
this.maleTree.getRoot().insert(new SearchTreeNode(candidate));
} else {
this.createTree(new SearchTreeNode(candidate));
}
}
} else {
if (this.maleTree != null) {
this.maleTree.getRoot().insert(new SearchTreeNode(candidate));
} else {
this.createTree(new SearchTreeNode(candidate));
}
}
} else {
if (this.maleTree != null) {
// If no match, add to opposite tree
SearchTreeNode match = this.maleTree.match(candidate);
if (match != null) {
this.maleTree.delete(match);
return new SimpleEntry<>( candidate, match.getKey() );
} else {
if (this.femaleTree != null) {
this.femaleTree.getRoot().insert(new SearchTreeNode(candidate));
} else {
this.createTree(new SearchTreeNode(candidate));
}
}
} else {
if (this.femaleTree != null) {
this.femaleTree.getRoot().insert(new SearchTreeNode(candidate));
} else {
this.createTree(new SearchTreeNode(candidate));
}
}
}
return null;
}
#Override
public List<Dancer> returnWaitingList() {
List<Dancer> resultList = new ArrayList<>();
if (femaleTree != null) resultList.addAll(femaleTree.getMembers());
if (maleTree != null) resultList.addAll(maleTree.getMembers());
return resultList;
}
SearchTree.java
import java.util.ArrayList;
import java.util.List;
class SearchTree {
private SearchTreeNode root;
private List<Dancer> members = new ArrayList<>();
SearchTree(SearchTreeNode node) {
this.root = node;
}
SearchTreeNode getRoot() {
return root;
}
SearchTreeNode match(Dancer d) {
return this.root.match(new SearchTreeNode(d));
}
void delete(SearchTreeNode tn) {
root = delete(root, tn);
}
private SearchTreeNode delete(SearchTreeNode n, SearchTreeNode tn) {
if (n == null) {
return null;
}
if (n == tn) {
// n is the node to be removed
if (n.getLeft() == null && n.getRight() == null) {
return null;
}
if (n.getLeft() == null) {
return n.getRight();
}
if (n.getRight() == null) {
return n.getLeft();
}
// if we get here, then n has 2 children
SearchTreeNode smallest = getLastOnTheLeft(n.getRight());
n.setKey(smallest.getKey());
n.setRight(delete(n.getRight(), smallest));
return n;
}
else if (tn.getKey().getHeight() < n.getKey().getHeight()) {
n.setLeft( delete(n.getLeft(), tn) );
return n;
}
else {
n.setRight( delete(n.getRight(), tn) );
return n;
}
}
private SearchTreeNode getLastOnTheLeft(SearchTreeNode start) {
SearchTreeNode candidate = null;
SearchTreeNode parent = null;
SearchTreeNode node = start;
while (node != null) {
if ( node.getLeft() != null ) {
parent = node;
candidate = node.getLeft();
}
node = node.getLeft();
}
if (parent != null) {
parent.setLeft(null);
}
return candidate;
}
List<Dancer> getMembers() {
members = new ArrayList<>();
preOrderTraversal(root);
return members;
}
private void preOrderTraversal(SearchTreeNode root){
if (root == null) {
return;
}
members.add(root.getKey());
preOrderTraversal(root.getLeft());
preOrderTraversal(root.getRight());
}
}
SearchTreeNode.java
public class SearchTreeNode {
private Dancer key;
private SearchTreeNode left;
private SearchTreeNode right;
SearchTreeNode(Dancer key) {
this.key = key;
this.left = null;
this.right = null;
}
void setKey(Dancer key) {
this.key = key;
}
Dancer getKey() {
return key;
}
void setLeft(SearchTreeNode left) {
this.left = left;
}
SearchTreeNode getLeft() {
return left;
}
void setRight(SearchTreeNode right) {
this.right = right;
}
SearchTreeNode getRight() {
return right;
}
void insert(SearchTreeNode node) {
if (node.key.getHeight() < this.key.getHeight()) {
if (left != null) {
left.insert(node);
} else {
this.setLeft(node);
}
} else {
if (right != null) {
this.getRight().insert(node);
} else {
this.setRight(node);
}
}
}
SearchTreeNode match(SearchTreeNode node) {
if (node.getKey().getGender().equals(Dancer.Gender.MALE)) {
if (key.getHeight() < node.getKey().getHeight()) {
if (right != null) {
return right.match(node);
} else {
return this;
}
} else {
if (left != null) {
return left.match(node);
} else {
return null;
}
}
} if (node.getKey().getGender().equals(Dancer.Gender.FEMALE)) {
if (key.getHeight() > node.getKey().getHeight()) {
if (left != null) {
return left.match(node);
} else {
return this;
}
} else {
if (right != null) {
return right.match(node);
} else {
return null;
}
}
}
return node;
}
#Override
public String toString() {
return "SearchTreeNode {" +
"key = " + key +
'}';
}
}

BST Node Deletion Confusion [JaVa]

I've created a Binary Search Tree in JaVa. Unfortunately 'delete' function doesn't work. I will be really appreciated if you could take a look. Thanks in advance..
Problem: I can't inorder print the tree after I delete a node from it.
Node:
class Node {
//Properties
private Node left, right, parent;
private int key;
//Getters and Setters
public Node(int key) {
this.key = key;
}
public int getKey() {
return key;
}
public void setKey(int key) {
this.key = key;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
public Node getParent() {
return parent;
}
public void setParent(Node parent) {
this.parent = parent;
}
}
Binary Search Tree:
public class BinarySearchTree {
//Properties
private Node root;
//Getters and Setters
Node getRoot() {
return root;
}
public void setRoot(Node root) {
this.root = root;
}
//Search Method
public Node search(Node x, int k){
if (x == null || k==x.getKey()){
return x;
}
if (k<x.getKey()){
return search(x.getLeft(), k);
}
else{
return search(x.getRight(), k);
}
}
//Insertion Method
public void insert(Node z) {
Node y = null;
Node x = getRoot();
while (x != null) {
y = x;
if (z.getKey() < x.getKey()) {
x = x.getLeft();
} else {
x = x.getRight();
}
}
z.setParent(y);
if (y == null) {
setRoot(z);
} else if (z.getKey() < y.getKey()) {
y.setLeft(z);
} else {
y.setRight(z);
}
}
//Printer Method
public void inorder(Node x) {
if (x != null) {
inorder(x.getLeft());
System.out.print(x.getKey() + " ");
inorder(x.getRight());
}
}
//Transplant Method
public void transplant(Node u, Node v){
if (u.getParent() == null){
setRoot(v);
}
else if (u==u.getParent().getLeft()){
u.getParent().setLeft(v);
}
else{
u.getParent().setRight(v);
}
if (v!=null){
v.setParent(u.getParent());
}
}
//Deletion Method
public void delete(Node x) {
if (x.getLeft() == null) {
transplant(x, x.getRight());
} else if (x.getRight() == null) {
transplant(x, x.getLeft());
} else {
Node y = minimum(x.getRight());
if (y.getParent() != x) {
transplant(y, y.getRight());
y.setRight(x.getRight());
y.getRight().setParent(y);
}
transplant(x, y);
y.setLeft(x.getLeft());
y.getLeft().setParent(y);
}
}
//Maximum Finder
public Node maximum(Node x) {
while (x.getRight() != null) {
x = x.getRight();
}
return x;
}
//Minimum Finder
public Node minimum(Node x) {
while (x.getLeft() != null) {
x = x.getLeft();
}
return x;
}
//Example Tree Constructor
public void createBST(int[] a){
for (int i=0; i<a.length; i++){
Node nodeToBeAdded = new Node(a[i]);
insert(nodeToBeAdded);
}
inorder(root);
}
}
and a Test class:
public class Test {
public static void main(String[] args) {
//CREATION
System.out.println("CREATION");
BinarySearchTree tree = new BinarySearchTree();
int[] a = {54, 32, 76, 7, 44, 63, 99};
tree.createBST(a);
System.out.println();
System.out.print("The root of the tree is: ");
System.out.println();
System.out.print("Maximum Node is: ");
tree.inorder(tree.maximum(tree.getRoot()));
System.out.println();
System.out.print("Minimum Node is: ");
tree.inorder(tree.minimum(tree.getRoot()));
System.out.println();
//INSERTION
System.out.println("INSERTION");
tree.insert(new Node(25));
tree.inorder(tree.getRoot());
tree.insert(new Node(485));
System.out.println();
tree.inorder(tree.getRoot());
tree.insert(new Node(12));
System.out.println();
tree.inorder(tree.getRoot());
tree.insert(new Node(5));
System.out.println();
tree.inorder(tree.getRoot());
tree.insert(new Node(9985));
System.out.println();
tree.inorder(tree.getRoot());
System.out.println();
System.out.print("Maximum Node is: ");
tree.inorder(tree.maximum(tree.getRoot()));
System.out.println();
System.out.print("Minimum Node is: ");
tree.inorder(tree.minimum(tree.getRoot()));
System.out.println();
//SEARCH
System.out.println("SEARCH");
tree.inorder(tree.search(tree.getRoot(), 32));
System.out.println();
//DELETION
System.out.println("DELETION");
tree.delete(new Node(5));
tree.inorder(tree.getRoot());
}
}
As i can see you don't override equals/hashCode methods so you can't find Node(5) because you created new instance. If you change your code in Test.java:
tree.insert(new Node(12));
System.out.println();
tree.inorder(tree.getRoot());
// Start changes
Node node5 = new Node(5);
tree.insert(node5);
System.out.println();
tree.inorder(tree.getRoot());
// End changes
tree.insert(new Node(9985));
// -cut some code
//DELETION
System.out.println("DELETION");
tree.delete(node5);
System.out.println();
tree.inorder(tree.getRoot());
it will print result

Implement multiset using sorted linkedList

Hello I implemented a multiset using a linkedlist and I want to implement the multiset using sorted linkedlist. This is multiset abstract class.
import java.io.PrintStream;
public abstract class Multiset<T> {
/**
* Delimiter string for print operation.
*/
protected static final String printDelim = " | ";
public abstract void add(T item);
public abstract int search(T item);
public abstract void removeOne(T item);
public abstract void removeAll(T item);
public abstract void print(PrintStream out);
}
This is my implementation of linkedlist.
import java.io.PrintStream;
public class LinkedListMultiset<T> extends Multiset<T> {
protected Node mHead;
protected int mLength;
public LinkedListMultiset() {
// Implement me!
mHead = null;
mLength = 0;
}
public void add(T item) {
Node newNode = new Node((String) item);
if (mHead == null)
mHead = newNode;
else {
Node currNode = mHead;
Node parentNode = null;
while (currNode != null) {
if (currNode.getValue().
equals(newNode.getValue())) {
currNode.addCounter();
return;
}
parentNode = currNode;
currNode = currNode.getNext();
}
parentNode.setNext(newNode);
}
mLength++;
}
public int search(T item) {
Node currNode = mHead;
while (currNode != null) {
if (currNode.getValue().equals((String) item)) {
return currNode.getCounter();
}
currNode = currNode.getNext();
}
return 0;
}
public void removeOne(T item) {
Node currNode = mHead;
Node lastNode = null;
while (currNode != null) {
if (currNode.getValue().equals((String) item)) {
currNode.minusCounter();
if (currNode.getCounter() == 0) {
if (currNode == mHead)
mHead = currNode.getNext();
else
lastNode.setNext
(currNode.getNext());
mLength--;
}
return;
}
lastNode = currNode;
currNode = currNode.getNext();
}
}
public void removeAll(T item) {
Node currNode = mHead;
Node lastNode = null;
while (currNode != null) {
if (currNode.getValue().equals((String) item)) {
if (currNode == mHead)
mHead = currNode.getNext();
else
lastNode.setNext(currNode.getNext());
mLength--;
return;
}
lastNode = currNode;
currNode = currNode.getNext();
}
}
public void print(PrintStream out) {
Node currNode = mHead;
while (currNode != null) {
out.printf("%s | %d\n", currNode.getValue()
, currNode.getCounter());
currNode = currNode.getNext();
}
}
private class Node {
protected String mValue;
protected Node mNext;
int counter;
public Node(String value) {
mValue = value;
mNext = null;
counter = 1;
}
public void addCounter() {
counter++;
}
public void minusCounter() {
counter--;
}
public int getCounter() {
return counter;
}
public String getValue() {
return mValue;
}
public Node getNext() {
return mNext;
}
public void setValue(String value) {
mValue = value;
}
public void setNext(Node next) {
mNext = next;
}
}
}
I want to implement sorted linkedlist but I want to change my code as minimum as possible.

Java Constructors: Actual and formal argument lists differ in length

So I was given an assignment in which I had to find and fix many errors in a somewhat large and sloppy code. I'm down to what looks to be the last one and I can't find the solution to this one. I've read similar scenarios where people get the same mistake but I can't relate them to my code. This is where I get the error: Temp = new BinaryNode(AId,AValue); saying
constructor BinaryNode in class BinaryNode cannot be applied to given
types;
Btree Class
package evidencia2datos;
public class BTree {
private BinaryNode Root;
private int NoOfNodes;
private BTree()
{
Root = null;
NoOfNodes = 0;
}
//operaciones
public boolean IsEmpty() //busca valor en NoOfNodes
{
return(NoOfNodes == 0);
}
public BinaryNode gRoot()
{
return Root;
}
public int Count() //valor de NoOfNodes
{
return NoOfNodes;
}
//size del arbol
public int Size(BinaryNode ATree)
{
if (ATree == null)
return 0;
else
return(1 + Size(ATree.gLeft()) + Size(ATree.gRight()));
}
//niveles
public int Height(BinaryNode ATree)
{
if (ATree == null)
return 0;
else
return (1 + Math.max(Height(ATree.gLeft()), Height(ATree.gRight())));
}
//traversales
public void PreOrder(BinaryNode ATree)
{
if (ATree != null)
{
System.out.println(ATree.gData());
PreOrder(ATree.gLeft());
PreOrder(ATree.gRight());
}
}
public void InOrder(BinaryNode ATree)
{
if (ATree != null)
{
InOrder(ATree.gLeft());
System.out.println(ATree.gData());
InOrder(ATree.gRight());
}
}
public void PostOrder(BinaryNode ATree)
{
if (ATree != null)
{
PostOrder(ATree.gLeft());
PostOrder(ATree.gRight());
System.out.println(ATree.gData());
}
}
//insertar valores
public void Insert(int AId, Object AValue)
{
BinaryNode Temp,Current,Parent;
if(Root == null)//tree is empty
{
Temp = new BinaryNode(AId,AValue);
Root = Temp;
NoOfNodes++;
}
else//tree is not empty
{
Temp = new BinaryNode(AId,AValue);
Current = Root;
while(true)//never ending while loop
{
Parent = Current;
if(AId < Current.gKey())
{//go left
Current = Current.gLeft();
if (Current == null)
{
Parent.sLeft(Temp);
NoOfNodes++;
return;//jump out of loop
}
}
else
{ //go right
Current = Current.gRight();
if(Current == null)
{
Parent.sRight(Temp);
NoOfNodes++;
return;
}
}
}
}
}
//search
public BinaryNode Find(int AKey)
{
BinaryNode Current = null;
if(!IsEmpty())
{
Current = Root; //start search at top of tree
while(Current.gKey() != AKey)
{
if(AKey < Current.gKey())
Current = Current.gLeft();
else
Current = Current.gRight();
if(Current == null)
return null;
}
}
return Current;
}
//succesor
public BinaryNode GetSuccessor(BinaryNode ANode)
{
BinaryNode Current,Successor,SuccessorParent;
Successor = ANode;
SuccessorParent = ANode;
Current = ANode.gRight();
while(Current !=null)
{
SuccessorParent = Successor;
Successor = Current;
Current = Current.gLeft();
}
if(Successor != ANode.gRight())
{
SuccessorParent.sLeft(Successor.gRight());
Successor.sRight(ANode.gRight());
}
return Successor;
}
public boolean Delete (int AKey)
{
BinaryNode Current, Parent;
boolean IsLeftChild = true;
Current = Root;
Parent = Root;
while (Current.gKey() != AKey)
{
Parent = Current;
if (AKey < Current.gKey())
{
IsLeftChild = true;
Current = Current.gLeft();
}
else
{
IsLeftChild = false;
Current = Current.gRight();
}
if(Current == null)
return false;
}
// if no children delete the node
if (Current.gLeft() == null && Current.gRight() == null)
{
if (Current == Root)
Root = Current.gLeft();
else
if (IsLeftChild)
Parent.sLeft(Current.gRight());
else
Parent.sRight(Current.gRight());
}
// if no right child replace with left subtree
else
{
if (Current.gRight() == null)
{
if (Current == Root)
Root = Current.gRight();
else
if (IsLeftChild)
Parent.sLeft(Current.gLeft());
else
Parent.sRight(Current.gLeft());
}
// if no left child replace with right subtree
else
{
if (Current.gLeft() == null)
{
if (Current == Root)
Root = Current.gLeft();
else
if (IsLeftChild)
Parent.sLeft(Current.gRight());
else
Parent.sRight(Current.gRight());
}
// two children so replace in order of successor
else
{
BinaryNode Successor = GetSuccessor(Current);
if (Current == Root)
Root = Successor;
else
if (IsLeftChild)
Parent.sLeft(Successor);
else
Parent.sRight(Successor);
Successor.sLeft(Current.gLeft());
}
}
}
NoOfNodes--;
return true;
}
public static void main(String[] args) {
BTree MyTree = new BTree();
BinaryNode NodeAt;
MyTree.Insert(12,"Jorge");
MyTree.Insert(4,"Andres");
MyTree.Insert(11,"Javier");
MyTree.Insert(1,"Jose");
MyTree.Insert(100,"Paty");
MyTree.Delete(1);
MyTree.InOrder(MyTree.gRoot());
NodeAt = MyTree.Find(11);
if(NodeAt !=null)
System.out.println("Data in Node with Key 11 = " + NodeAt.gData());
System.exit(0);
}
}
BinaryNode Class
package evidencia2datos;
public class BinaryNode {
private int Key;
private Object Data;
private BinaryNode Left;
private BinaryNode Right;
public BinaryNode()
{
java.util.Scanner scaniar = new java.util.Scanner(System.in);
System.out.print("Enter in Key Value: ");
Key = scaniar.nextInt();
System.out.print("Enter in data: ");
Data = scaniar.nextInt();
Left = null;
Right = null;
}
//get
public int gKey()
{
return Key;
}
public Object gData()
{
return Data;
}
public BinaryNode gLeft()
{
return Left;
}
public BinaryNode gRight()
{
return Right;
}
//set
public void sKey(int AValue)
{
Key = AValue;
}
public void sData(Object AValue)
{
Data = AValue;
}
public void sLeft( BinaryNode AValue)
{
Left = AValue;
}
public void sRight( BinaryNode AValue)
{
Right = AValue;
}
}
You can create a new BinaryNode constructor which takes two arguments
BinaryNode (){
...
}
//Este es el nuevo constructor, como se puede observar
//toma dos argumentos
BinaryNode (int k, Object d){
key = k;
data = d;
...
}
I hope this will help you.

Why will my program not go into my while loop?

I'm working on a program that will take a name and number of a periodic element, store it in a tree and then print it out in different orders.
When I try and run my main class it asks for the name, but then it doesn't go into the while loop.
Here is my main class.
public class BinarySearchTree
{
public static void main(String[] args)
{
Scanner conIn = new Scanner(System.in);
String name;
int atomicNum;
BSTInterface<PeriodicElement> elements = new BSTree<PeriodicElement>();
PeriodicElement element;
int numElements;
String skip;
System.out.print("Element name (press Enter to end): ");
name = conIn.nextLine();
while (!name.equals(""));
{
System.out.print("Atomic Number: ");
atomicNum = conIn.nextInt();
skip = conIn.nextLine();
element = new PeriodicElement(name, atomicNum);
elements.add(element);
System.out.print("Element name (press ENTER TO END): ");
name = conIn.nextLine();
}
System.out.println();
System.out.println("Periodic Elements");
numElements = elements.reset(BSTree.INORDER);
for (int count = 1; count <= numElements; count++)
{
System.out.println(elements.getNext(BSTree.INORDER));
}
}
}
Here is my Binary Search Tree
public class BSTree <T extends Comparable<T>>
implements BSTInterface<T>
{
protected BSTNode<T> root;
boolean found;
protected LinkedUnbndQueue<T> inOrderQueue;
protected LinkedUnbndQueue<T> preOrderQueue;
protected LinkedUnbndQueue<T> postOrderQueue;
public BSTree()
{
root = null;
}
public boolean isEmpty()
{
return (root == null);
}
private int recSize(BSTNode<T> tree)
{
if(tree == null)
{
return 0;
}
else
{
return recSize(tree.getLeft()) + recSize(tree.getRight()) + 1;
}
}
public int size()
{
int count = 0;
{
if(root != null)
{
LinkedStack<BSTNode<T>> hold = new LinkedStack<BSTNode<T>>();
BSTNode<T> currNode;
hold.push(root);
while(!hold.isEmpty())
{
currNode = hold.top();
hold.pop();
count++;
if(currNode.getLeft() != null)
{
hold.push(currNode.getLeft());
}
if(currNode.getRight() != null)
{
hold.push(currNode.getRight());
}
}
}
//System.out.println(count);
return count;
}
}
public boolean recContains(T element, BSTNode<T> tree)
{
if(tree == null)
{
return false;
}
else if(element.compareTo(tree.getInfo()) < 0)
{
return recContains(element, tree.getLeft());
}
else if(element.compareTo(tree.getInfo()) > 0)
{
return recContains(element, tree.getRight());
}
else
{
return true;
}
}
public boolean contains (T element)
{
//System.out.println("Tree contains: " + recContains(element, root));
return recContains(element, root);
}
public T recGet(T element, BSTNode<T> tree)
{
if(tree == null)
{
return null;
}
else if(element.compareTo(tree.getInfo()) < 0)
{
return recGet(element, tree.getLeft());
}
else if(element.compareTo(tree.getInfo()) > 0)
{
return recGet(element, tree.getRight());
}
else
{
return tree.getInfo();
}
}
public T get(T element)
{
//System.out.println(recGet(element, root));
return recGet(element, root);
}
public void add(T element)
{
root = recAdd(element, root);
}
private BSTNode<T> recAdd(T element, BSTNode<T> tree)
{
if(tree == null)
{
tree = new BSTNode<T>(element);
}
else if(element.compareTo(tree.getInfo()) <= 0)
{
tree.setLeft(recAdd(element, tree.getLeft()));
}
else
{
tree.setRight(recAdd(element, tree.getRight()));
}
return tree;
}
public boolean remove(T element)
{
root = recRemove(element, root);
return found;
}
private BSTNode<T> recRemove(T element, BSTNode<T> tree)
{
if(tree == null)
{
found = false;
}
else if (element.compareTo(tree.getInfo()) < 0)
{
tree.setLeft(recRemove(element, tree.getLeft()));
}
else if (element.compareTo(tree.getInfo()) > 0)
{
tree.setRight(recRemove(element, tree.getRight()));
}
else
{
tree = removeNode(tree);
found = true;
}
return tree;
}
private BSTNode<T> removeNode(BSTNode<T> tree)
{
T data;
if(tree.getLeft() == null)
{
return tree.getRight();
}
else if(tree.getRight() == null)
{
return tree.getLeft();
}
else
{
data = getPredecessor(tree.getLeft());
tree.setInfo(data);
tree.setLeft(recRemove(data, tree.getLeft()));
return tree;
}
}
private T getPredecessor(BSTNode<T> tree)
{
while (tree.getRight() != null)
{
tree = tree.getRight();
}
return tree.getInfo();
}
public int reset(int orderType)
{
int numNodes = size();
if(orderType == INORDER)
{
inOrderQueue = new LinkedUnbndQueue<T>(numNodes);
}
else
{
if(orderType == PREORDER)
{
preOrderQueue = new LinkedUnbndQueue<T>(numNodes);
preOrder(root);
}
if(orderType == POSTORDER)
{
postOrderQueue = new LinkedUnbndQueue<T>(numNodes);
postOrder(root);
}
}
return numNodes;
}
public T getNext(int orderType)
{
if(orderType == INORDER)
{
return inOrderQueue.dequeue();
}
else
{
if(orderType == PREORDER)
{
return preOrderQueue.dequeue();
}
else
{
if(orderType == POSTORDER)
{
return postOrderQueue.dequeue();
}
else
{
return null;
}
}
}
}
private void inOrder(BSTNode<T> tree)
{
if(tree != null)
{
inOrder(tree.getLeft());
inOrderQueue.enqueue(tree.getInfo());
inOrder(tree.getRight());
}
}
private void preOrder(BSTNode<T> tree)
{
if(tree != null)
{
preOrderQueue.enqueue(tree.getInfo());
preOrder(tree.getLeft());
preOrder(tree.getRight());
}
}
private void postOrder(BSTNode<T> tree)
{
if(tree != null)
{
postOrder(tree.getLeft());
postOrder(tree.getRight());
postOrderQueue.enqueue(tree.getInfo());
}
}
}
Here is the Binary Search Tree Node class
public class BSTNode <T extends Comparable<T>>
{
protected T info;
protected BSTNode<T> left;
protected BSTNode<T> right;
public BSTNode(T info)
{
this.info = info;
left = null;
right = null;
}
public void setInfo(T info)
{
this.info = info;
}
public T getInfo()
{
return info;
}
public void setLeft(BSTNode<T> link)
{
left = link;
}
public void setRight(BSTNode<T> link)
{
right = link;
}
public BSTNode<T> getLeft()
{
return left;
}
public BSTNode<T> getRight()
{
return right;
}
}
Remove the semi-colon that is terminating the while statement
while (!name.equals(""));
^
Remove the semi colon after the while statment because a semi colon makes it end there while a { is the start if while something is true or not (!) and it should end as you obviously know with a }.

Categories