Binary Trees: In-order Iterator: Java - java

How would I go about writing an iterator to iterate over each value of a binary tree in "in-order" fashion? I should be using a stack. BinaryNode is a simple node class with pointers to "left" and "right" nodes. Here is what I have so far:
class InOrderIterator implements Iterator<T> {
private Stack<BinaryNode> stack;
public InOrderIterator(BinarySearchTree<T>.BinaryNode root) {
stack = new Stack<BinaryNode>();
stack.push(root);
}
#Override
public boolean hasNext() {
while (!this.stack.isEmpty() && stack.peek() == NULL_NODE)
this.stack.pop();
return !this.stack.isEmpty();
}
#Override
public T next() {
//TODO
if (!this.hasNext())
throw new NoSuchElementException("No more nodes in tree!");
BinaryNode current = this.stack.pop();
BinaryNode output = null;
while(current != NULL_NODE){
this.stack.push(current);
current = current.left;
}
if(current == NULL_NODE){
if(!this.stack.isEmpty()){
output = this.stack.pop();
return output.data;
}
}
return null;
}
}
I have the basic algorithm down, but I can't seem to convert it to java code.

Think about invariants. You have a stack of nodes. What does it mean for a node to be on the stack?
Might I suggest: A node on the stack represents a "half-tree", a node and its entire right subtree, and the stack holds all the half-trees that together make up all the nodes that have not been returned from next() yet.
In what order should those half-trees be pushed on the stack? Answering that question gives you your invariant condition, the property that will be preserved as your code runs.
Satisfy yourself that your invariant implies that the top of the stack must be whatever next() is going to return next. When you pop it off to return it, you're going to have to somehow deal with its right subtree before returning. From your invariant, it should be obvious how to do that.
If you don't consciously and explicitly think about what your variables mean and what your invariants are, your coding efforts are going to be undirected. You're going to flail around, writing spaghetti code. Once you've done that, though, the code will write itself.

public class BinaryTreeNode {
private int element; //element stored at this node
private BinaryTreeNode left, right;
public BinaryTreeNode() { }
public BinaryTreeNode(int element) {
setElement(element);
setLeft(null);
setRight(null);
}
//returns the elements stored at this position
public int element() {
return element;
}
//sets the elements stored at this position
public void setElement(int e) {
element = e;
}
//return the left child of this position
public BinaryTreeNode getLeft() {
return left;
}
//set the left chid of this position
public void setLeft(BinaryTreeNode l) {
left = l;
}
//return the right child of this position
public BinaryTreeNode getRight() {
return right;
}
//sets the right child of this position
public void setRight(BinaryTreeNode r) {
right = r;
}
}
public class TestBTN {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
BinaryTreeNode root = null, right, left, node = null;
int arrayInt[] = {25, 20, 7, 13, 33, 50, 45, 17, 30, 55};
for (int i = 0; i < arrayInt.length; i++) {
if (root == null) {
root = node = new BinaryTreeNode(arrayInt[0]);
}//endIf
else {
node = new BinaryTreeNode(arrayInt[i]);
BinaryTreeNode s, p;
p = s = root;
while (s != null) {
p = s;
if (node.element() > s.element()) {
s = s.getRight();
} else {
s = s.getLeft();
}
}//endWhile
if (node.element() > p.element()) {
p.setRight(node);
} else {
p.setLeft(node);
}
}//emdElse
}//endFor
//printing
//Print(root);
//PostOrder(root);
//PreOrder(root);
InOrder(root);
//System.out.println("\nBinaryTreeNode");
}//endMain
private static void Print(BinaryTreeNode node) {
if (node != null) {
System.out.print(node.element() + " ");
Print(node.getLeft());
Print(node.getRight());
}//endIf
}//endPrint
static void PostOrder(BinaryTreeNode ptr) {
if(ptr != null) {
PostOrder(ptr.getLeft());
PostOrder(ptr.getRight());
System.out.print(ptr.element()+" ");
}//endIf
}//endPost
static void PreOrder(BinaryTreeNode ptr) {
if(ptr != null) {
System.out.print(ptr.element()+" ");
PreOrder(ptr.getLeft());
PreOrder(ptr.getRight());
}
}
static void InOrder(BinaryTreeNode ptr) {
if(ptr != null) {
InOrder(ptr.getLeft());
System.out.print(ptr.element()+" ");
InOrder(ptr.getRight());
}
}
}

Related

Remove method in a binary tree

I'm trying to create a method to remove nodes from a Binary Tree but I am having a problem, it seems to be ok but I have another method for printing all of them and after "deleting" a specific node I use the print method but it prints all of them including the one I've already deleted.
public class BinaryTree
{
Node root;
Node n;
private class Node
{
public Node f; //father
public Node right;
public Node left;
public int key; // key
public String Student;
public int Mark;
public Node(int key)
{
right = null;
left = null;
f = null;
Student = null;
Mark = 0;
}
}
public void remove()
{
System.out.println("");
System.out.println("Which student do you want to delete? Write down his ID.");
int id = Genio.getInteger();
n = new Node(id);
Node temporal = root;
if(root == null)
{
System.out.println("This tree is empty");
}
else
{
while(temporal != null)
{
n.f = temporal;
if(n.key == temporal.key)
{
if(n.f.right == null && n.f.left == null)
{
n = null;
temporal = null;
}
}
else if(n.key >= temporal.key)
{
temporal = temporal.right;
}
else
{
temporal = temporal.left;
}
}
}
}
}

How can i insert an item at root in a binary search tree in java?

I want to insert a new item in the root of a binary search tree. Below, i present the method for this and the helping methods for left and right rotation.I think there is a mistake there cause when (using the method below) try to print the tree with an inorder traverse, it stops just behind the new root, so it doesn't print the new root and the items in the right side of the root. I have checked the print method after inserting in a normal way items to the tree and it works, so i don't think there is a problem there.
public class ST {
private TreeNode root;
public ST() {
this.size = 0;
this.root = null;
}
public void insert_at_root(Suspect item) {
insert_at_rootRec(item, this.root);
}
private TreeNode insert_at_rootRec(Suspect item, TreeNode head) {
if (head == null)
return new TreeNode(item);
if (item.key() < head.item.key()) {
head.left = insert_at_rootRec(item, head.left);
head = rotateRight(head);
} else {
head.right = insert_at_rootRec(item, head.right);
head = rotateLeft(head);
}
return head;
}
private TreeNode rotateRight(TreeNode h) {
TreeNode x = h.left;
h.left = x.right;
x.right = h;
return x;
}
private TreeNode rotateLeft(TreeNode h) {
TreeNode x = h.right;
h.right = x.left;
x.left = h;
return x;
}
public void printTreeByAFM(PrintStream stream) {
printTreeByAFMRec(this.root, stream);
}
private void printTreeByAFMRec(TreeNode root, PrintStream stream) {
if (root == null)
return;
printTreeByAFMRec(root.left, stream);
stream.println(root.item);
printTreeByAFMRec(root.right, stream);
}
}
You should save the new tree you calculate inside insert_at_root:
public void insert_at_root(Suspect item) {
root = insert_at_rootRec(item, this.root);
}
You are not doing anything with the return of insert_at_rootRec(), so after you compute the new tree, it just goes to the garbage collector.

Queue Scenario Help Getting Started

Hi I am currently working on a queue wait time simultaion, over the course of 12 hours that adds a random number of people per line every minute while removing three from the front every minute as well. After the twelve hours are over i will average the rate in which they entered and exited the line. I need to perform this 50 times to get a more accurate model simulation. I do not currently know how to properly implement this. If i could get some pointers on where to begin it would be most appreciated.
Linked List Class
public class LinkedListQueue<E>{
private Node<E> head;
private Node<E> tail;
private int size;
public LinkedListQueue() {
}
public void enqueue(E element) {
Node newNode = new Node(element, null);
if (size == 0) {
head = newNode;
} else {
tail.setNextNode(newNode);
}
tail = newNode;
size++;
}
public E dequeue() {
if (head != null) {
E element = head.getElement();
head = head.getNextNode();
size--;
if (size == 0) {
tail = null;
}
return element;
}
return null;
}
public E first() {
if (head != null) {
return head.getElement();
}
return null;
}
public int getSize() {
return size;
}
public void print() {
if (head != null) {
Node currentNode = head;
do {
System.out.println(currentNode.toString());
currentNode = currentNode.getNextNode();
} while (currentNode != null);
}
System.out.println();
}
}
Node Class
public class Node<E>{
private E element;
private Node<E> next;
public Node(E element, Node next) {
this.element = element;
this.next = next;
}
public void setNextNode(Node next) {
this.next = next;
}
public Node<E> getNextNode() {
return next;
}
public E getElement() {
return element;
}
public String toString() {
return element.toString();
}
}
Simulation Class
import java.util.Random;
public class Simulation {
private int arrivalRate;
//you'll need other instance variables
public Simulation(int arrivalRate, int maxNumQueues) {
this.arrivalRate = arrivalRate;
}
public void runSimulation() {
//this is an example for using getRandomNumPeople
//you are going to remove this whole loop.
for (int i = 0; i < 10; i++) {
int numPeople = getRandomNumPeople(arrivalRate);
System.out.println("The number of people that arrived in minute " + i + " is: " + numPeople);
}
}
//Don't change this method.
private static int getRandomNumPeople(double avg) {
Random r = new Random();
double L = Math.exp(-avg);
int k = 0;
double p = 1.0;
do {
p = p * r.nextDouble();
k++;
} while (p > L);
return k - 1;
}
//Don't change the main method.
public static void main(String[] args) {
Simulation s = new Simulation(18, 10);
s.runSimulation();
}
}
It looks like you haven't started this assignment at all.
First, start with the main() method. A new Simulation object is created. Follow the constructor call to new Simulation(18, 10). For starters, you will see that the constructor is incomplete
public Simulation(int arrivalRate, int maxNumQueues) {
this.arrivalRate = arrivalRate;
// missing the handling of maxNumQueues
}
So, for starters, you probably want to define a new variable of type integer (since that is what is the type of maxNumQueues according to the Simulation constructor) in the Simulation class. From there, you obviously want to get back into the constructor and set your new variable to reference the constructor call.
Example:
public class Simulation {
private int arrivalRate;
private int maxNumQueues; // keep track of the maxNumQueues
public Simulation(int arrivalRate, int maxNumQueues) {
this.arrivalRate = arrivalRate;
this.maxNumQueues = maxNumQueues; // initialize our new local variable maxNumQueues
}}

LinkedList class. (ReflectiveOperationException)

I am learning Java SE and am currently at simple linked lists (page 687/1047 of Savitch's Absolute Java).
I am stuck at instantiating the LinkList in the main method of my demo class:
LinkedList1 list = new LinkedList1();
I tried using breakpoint and it indicates a ReflectiveOperationException.
This is the code:
public class Node1
{
private String item;
private int count;
private Node1 link;
public Node1()
{
link = null;
item = null;
count = 0;
}
public Node1(String newItem, int newCount, Node1 linkValue)
{
setData(newItem, newCount);
link = linkValue;
}
public void setData(String newItem, int newCount)
{
item = newItem;
count = newCount;
}
public void setLink(Node1 newLink)
{
link = newLink;
}
public String getItem()
{
return item;
}
public int getCount()
{
return count;
}
public Node1 getLink()
{
return link;
}
}
This is the LinkedList1 class:
public class LinkedList1
{
private Node1 head;
public LinkedList1()
{
head = null;
}
/**
* Adds a node at the start of the list with the specified data.
* The added node will be the first node in the list.
*/
public void add(String itemName, int itemCount)
{
head = new Node1(itemName, itemCount, head);
}
/**
* Removes the head node and returns true if the list contains at least
* one node. Returns false if the list is empty.
*/
public boolean deleteHeadNode()
{
if (head != null)
{
head = head.getLink();
return true;
}
else
return false;
}
/**
* Returns the number of nodes in the list.
*/
public int size()
{
int count = 0;
Node1 position = head;
while (position != null)
{
count++;
head = position.getLink();
}
return count;
}
public boolean contains(String item)
{
return (find(item) != null);
}
/**
* Finds the first node containing the target item, and returns a
* reference to that node. If the target is not in the list, null is returned.
*/
public Node1 find(String target)
{
Node1 position = head;
String itemAtPosition;
while(position != null)
{
itemAtPosition = position.getItem();
if(itemAtPosition.equals(target))
{
return position;
}
position = position.getLink();
}
return null; //target was not found
}
public void outputList()
{
Node1 position = head;
while (position != null)
{
System.out.println(position.getItem() + " " + position.getCount());
position = position.getLink();
}
}
}
I think that the problem has something to do with the constructor of Node1 having the member link of type Node1. I'm trying to understand how these data structures work and not just resort to using the built-in ArrayList(& APIs) for my projects. Can you guys have a look and point me in the right direction. Any help would be very much appreciated.
This is my main method.
public class LinkedListDemo
{
public static void main(String[] args)
{
try
{
LinkedList1 list = new LinkedList1();
list.add("apples", 1);
list.add("bananas", 2);
list.add("cantaloupe", 3);
System.out.println("List has "+ list.size() + " nodes.");
list.outputList();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
Your size method contains an infinite loop which explain why the outputs are never reached.
while (position != null)
{
count++;
head = position.getLink();
}
You are looping until position is null, but never assign anything to position and instead assign to head. Instead, you want to do
while (position != null)
{
count++;
position = position.getLink();
}
Now you would get the output
List has 3 nodes.
cantaloupe 3
bananas 2
apples 1

A method to print a binary search tree (BST) from the largest element to the smallest

I think I have to modify one of the traversals. I tried modifying one that print from the smallest to the largest which is this one
private void printTree(BinaryTreeNode t) {
if (t != null) {
printTree(t.llink);
System.out.print(" " + t.info);
printTree(t.rlink);
}
}
But it didn't work. I'm still stuck on what I should try next. This the binary search tree I'm using:
public class BinarySearchTree extends BinaryTree {
//Default constructor.
//Postcondition: root = null;
public BinarySearchTree() {
super();
}
//Copy constructor.
public BinarySearchTree(BinarySearchTree otherTree) {
super(otherTree);
}
public class BinaryTree {
//Definition of the node
protected class BinaryTreeNode {
DataElement info;
BinaryTreeNode llink;
public DataElement getInfo() {
return info;
}
public BinaryTreeNode getLlink() {
return llink;
}
public BinaryTreeNode getRlink() {
return rlink;
}
BinaryTreeNode rlink;
}
protected BinaryTreeNode root;
//Default constructor
//Postcondition: root = null;
public BinaryTree() {
root = null;
}
//Copy constructor
public BinaryTree(BinaryTree otherTree) {
if (otherTree.root == null) //otherTree is empty.
{
root = null;
}
else {
root = copy(otherTree.root);
}
}
public BinaryTreeNode getRoot() {
return root;
}
The code you have posted looks OK for sorting from smallest to largest.
If you want to sort the other way around, then the following code should work:
private void printTree(BinaryTreeNode t) {
if (t != null) {
printTree(t.rlink);
System.out.print(" " + t.info);
printTree(t.llink);
}
}
All you have to do it swap the llink and rlink. To print the tree from largest to smallest, you can use one of the trees traversal methods. for example, the one that suits this case is the Inorder traversal because it prints the tree from smallest to largest in terms of values. All you have to do is the following:
if(t!=null){
printTree(t.rlink);
System.out.print(" " + t.info);
printTree(t.llink);
}
That should print it from largest to smallest.

Categories

Resources