So I have to modify the BST class to include a PrintRange function, which would essentially print all nodes between two values in order.
Here is the class
/** Source code example for "A Practical Introduction to Data
Structures and Algorithm Analysis, 3rd Edition (Java)"
by Clifford A. Shaffer
Copyright 2008-2011 by Clifford A. Shaffer
*/
import java.lang.Comparable;
/** Binary Search Tree implementation for Dictionary ADT */
class BST<Key extends Comparable<? super Key>, E>
implements Dictionary<Key, E> {
private BSTNode<Key,E> root; // Root of the BST
int nodecount; // Number of nodes in the BST
/** Constructor */
BST() { root = null; nodecount = 0; }
/** Reinitialize tree */
public void clear() { root = null; nodecount = 0; }
/** Insert a record into the tree.
#param k Key value of the record.
#param e The record to insert. */
public void insert(Key k, E e) {
root = inserthelp(root, k, e);
nodecount++;
}
// Return root
public BSTNode getRoot()
{
return root;
}
/** Remove a record from the tree.
#param k Key value of record to remove.
#return The record removed, null if there is none. */
public E remove(Key k) {
E temp = findhelp(root, k); // First find it
if (temp != null) {
root = removehelp(root, k); // Now remove it
nodecount--;
}
return temp;
}
/** Remove and return the root node from the dictionary.
#return The record removed, null if tree is empty. */
public E removeAny() {
if (root == null) return null;
E temp = root.element();
root = removehelp(root, root.key());
nodecount--;
return temp;
}
/** #return Record with key value k, null if none exist.
#param k The key value to find. */
public E find(Key k) { return findhelp(root, k); }
/** #return The number of records in the dictionary. */
public int size() { return nodecount; }
private E findhelp(BSTNode<Key,E> rt, Key k) {
if (rt == null) return null;
if (rt.key().compareTo(k) > 0)
return findhelp(rt.left(), k);
else if (rt.key().compareTo(k) == 0) return rt.element();
else return findhelp(rt.right(), k);
}
/** #return The current subtree, modified to contain
the new item */
private BSTNode<Key,E> inserthelp(BSTNode<Key,E> rt,
Key k, E e) {
if (rt == null) return new BSTNode<Key,E>(k, e);
if (rt.key().compareTo(k) > 0)
rt.setLeft(inserthelp(rt.left(), k, e));
else
rt.setRight(inserthelp(rt.right(), k, e));
return rt;
}
/** Remove a node with key value k
#return The tree with the node removed */
private BSTNode<Key,E> removehelp(BSTNode<Key,E> rt,Key k) {
if (rt == null) return null;
if (rt.key().compareTo(k) > 0)
rt.setLeft(removehelp(rt.left(), k));
else if (rt.key().compareTo(k) < 0)
rt.setRight(removehelp(rt.right(), k));
else { // Found it
if (rt.left() == null) return rt.right();
else if (rt.right() == null) return rt.left();
else { // Two children
BSTNode<Key,E> temp = getmin(rt.right());
rt.setElement(temp.element());
rt.setKey(temp.key());
rt.setRight(deletemin(rt.right()));
}
}
return rt;
}
private BSTNode<Key,E> getmin(BSTNode<Key,E> rt) {
if (rt.left() == null) return rt;
return getmin(rt.left());
}
private BSTNode<Key,E> deletemin(BSTNode<Key,E> rt) {
if (rt.left() == null) return rt.right();
rt.setLeft(deletemin(rt.left()));
return rt;
}
private void printhelp(BSTNode<Key,E> rt) {
if (rt == null) return;
printhelp(rt.left());
printVisit(rt.element());
printhelp(rt.right());
}
private StringBuffer out;
public String toString() {
out = new StringBuffer(400);
printhelp(root);
return out.toString();
}
private void printVisit(E it) {
out.append(it + "\n");
}
public void printPreOrder(BSTNode<E, E> root) {
if (root != null) {
System.out.println(root.element());
printPreOrder(root.left());
printPreOrder(root.right());
}
}
public void printInOrder(BSTNode<E, E> root) {
if (root != null) {
printInOrder(root.left());
System.out.println(root.element());
printInOrder(root.right());
}
}
public void printPostOrder(BSTNode<E, E> root) {
if (root != null) {
printPostOrder(root.left());
printPostOrder(root.right());
System.out.println(root.element());
}
}
}
Here's what I have so far for the PrintRange function:
public void printRange(BSTNode<E, E> root, E low, E high) {
if (root != null) {
printRange(root.left(), low, high);
if (root.element().toString().compareTo(low.toString()) > 0 && root.element().toString().compareTo(high.toString()) < 0)
System.out.println(root.element());
printRange(root.right(), low, high);
}
}
But it's giving me an error. Any suggestions on how to compare elements/nodes/I'm not even certain in a BST?
Here's the driver if it helps
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Lab8a {
public static void main(String[] args) {
BST<String, String> tree = new BST<String, String>();
Scanner fileScan = null, scan = new Scanner(System.in);
//Open file
try {
fileScan = new Scanner(new File("inventory.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Reads elements from file
while (fileScan.hasNextLine()) {
String s = fileScan.nextLine();
tree.insert(s, s);
}
System.out.println("\nRange");
tree.printRange(tree.getRoot(), "A", "B");
}
}
And the text file:
CT16C1288B
DT14B1225F
MI15B1250A
MI15B1251A
HO03N1095A
HY07D1095BQ
KI04D2593C
DG12A1240AQ
HY03G2593BQ
TO30A1310A
HO03N1095AQ
HO01H1351C
HO01H1350C
FT18A1288B
LR15A1000A
BM12E1000A
VW02B3113A
NI23H1230AQ
LX03D2503A
LX03D2502A
LX03D2502A
VW22A3113B
VW22B3113A
I was mistaken. There was no error. I must have fixed the code at some point.
Related
package linkedList.list;
import linkedList.node.ListNode;
public interface LinkedList<N extends ListNode<T>,T>
{
public boolean isEmpty();
public int size();
public String toString();
public T[] toArray(Class<? extends T> cl);
public LinkedList<N,T> fromArray(T[] array) throws ListAccessError;
}
package linkedList.list;
import linkedList.node.ListNode;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
public abstract class BasicList<N extends ListNode<T>,T> implements LinkedList<N,T> {
N root;
int size;
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
public N getRoot() {
return root;
}
public void setRoot(N newRoot) {
root = newRoot;
}
public T[] toArray(Class<? extends T> cl) {
T[] array = (T[]) Array.newInstance(cl,size());
ListNode<T> node = getRoot();
for (int index = 0; index < size(); index++) {
array[index] = node.getValue();
node = node.getNext();
}
return array;
}
public String toString() {
if (isEmpty()) {
return "[]";
} else {
ListNode<T> currentNode = getRoot();
StringBuilder string = new StringBuilder("[" + currentNode.getValue());
while ((currentNode = currentNode.getNext()) != null) {
string.append("," + currentNode.getValue());
}
string.append("]");
return string.toString();
}
}
public String toString(int n) {
if (isEmpty()) {
return "[]";
} else {
ListNode<T> currentNode = getRoot();
StringBuilder string = new StringBuilder("[" + currentNode.getValue());
int added = 0;
while (added < n && (currentNode = currentNode.getNext()) != null) {
string.append("," + currentNode.getValue());
added++;
}
if (currentNode != null) {
string.append(",...");
}
string.append("]");
return string.toString();
}
}
}
package linkedList.list;
import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader;
import jdk.nashorn.internal.ir.IfNode;
import linkedList.node.ListNode;
import linkedList.node.SingleLinkNode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class SingleLinkList<T> extends BasicList<SingleLinkNode<T>,T> implements List<T> {
public SingleLinkList<T> fromArray(T[] array) throws ListAccessError {
for (int index = array.length-1; index >= 0; index--) {
add(0,array[index]);
}
return this;
}
ListNode<T> getNode(int index) throws ListAccessError {
// Is the list empty? If so, cannot access the node.
if (isEmpty()) {
throw new ListAccessError("Cannot get node. List is empty.");
}
// Is the given index negative? If so, this is an error.
if (index < 0) {
throw new ListAccessError("Cannot get node. Negative index.");
}
ListNode<T> currentNode = getRoot(); // start at the root
while (index != 0 && currentNode != null) { // walk along the list (if haven't reached the end by hitting null node)
currentNode = currentNode.getNext(); // by gettting next node in the list
index--; // and reducing index by one
}
// Reached the end of the list (by hitting null node)? If so, cannot access the required node.
if (currentNode == null) {
throw new ListAccessError("Cannot get node. Not enough nodes in the list.");
}
// Successfully found node by walking through until index was zero.
return currentNode;
}
public T get(int index) throws ListAccessError {
return getNode(index).getValue();
}
#Override
public void add(int index, T value) throws ListAccessError {
if (index > size() || index < 0) {
throw new ListAccessError("Index bigger than size.");
}
SingleLinkNode<T> newNode = new SingleLinkNode<T>(value);
SingleLinkNode<T> current = getRoot();
if(index==0) {
setRoot(newNode);
newNode.setNext(current);
size++;
} else {
while(--index > 0) {
current = current.getNext();
}
newNode.setNext(current.getNext());
current.setNext(newNode);
size++;
}
}
#Override
public T remove(int index) throws ListAccessError {
if (index >= size() || index < 0) {
throw new ListAccessError("Index out of bounds");
}
if (isEmpty()) {
throw new ListAccessError("List is empty cannot remove from list");
}
SingleLinkNode<T> current = getRoot();
SingleLinkNode<T> nextItem = getRoot().getNext();
return null;
}
}
package linkedList.node;
public class SingleLinkNode<T> implements ListNode<T>
{
private T value;
private SingleLinkNode<T> next;
public SingleLinkNode(T value) {
this.value = value;
next = null;
}
public SingleLinkNode(T value, SingleLinkNode<T> next) {
this.value = value;
this.next = next;
}
public T getValue() {
return value;
}
#Override
public void setValue(T value) {
this.value = value;
}
public SingleLinkNode<T> getNext() {
return next;
}
#Override
public void setNext(ListNode<T> node) {
next = (SingleLinkNode<T>) node;
}
public String toString() {
return value + (getNext() != null ? "=>" + getNext() : "");
}
}
I have just implemented the add method which takes the index and the value and inserts it into that position in the List. However when researching how to remove at the index I am unable to find anything that removes the node with just the given index. Any help is welcome and thanks in advance for any solutions!
When removing a node from a linked list at I position all you need to do is
Get to the node at i-1, let's name it 'n1'
Get the node n2=n1.next.next
Make n1.next =n2
You simply remove the "link" to the requested node at i and it's no longer part of the linked list.
Firstly, you have to check if this it is 0-th index you have to remove, so you have to shift root. Then for removing node at i-th root, all you have to do this:
nodeBeforeI.setNext(nodeBeforeI.getNext().getNext());
The complete code:
public T remove(int index) throws ListAccessError {
if (index >= size() || index < 0) {
throw new ListAccessError("Index out of bounds");
}
if (isEmpty()) {
throw new ListAccessError("List is empty cannot remove from list");
}
SingleLinkNode<T> current = getRoot();
SingleLinkNode<T> removed;
if (index == 0){
removed = current;
setRoot(current.getNext()); // setting root to root.next
}else{
for (int i = 0; i < index -1; i++){
current = current.getNext();
}
removed = current.getNext();
current.setNext(current.getNext().getNext());
}
return removed.getValue();
}
I've been struggling with implementing a Binary Search Tree with the Iterator method. I've been checking out this algorithm out on WikiPedia:
def search_recursively(key, node):
if node is None or node.key == key:
return node
if key < node.key:
return search_recursively(key, node.left)
# key > node.key
return search_recursively(key, node.right)
I translated it to Java:
public Iterator<T> iterator()
{
return new Iterator<T>()
{
private int count = 0;
#Override
public boolean hasNext()
{
return count++ < size;
}
#Override
public T next()
{
return search(root, root.word);
}
public T search(BST root, T word)
{
if (root == null || root.word.compareTo(word) == 0)
{
return root.word;
}
if (root.word.compareTo(word) < 0)
{
return search(root.left, word);
}
return search(root.right, word);
}
};
When trying to run the program I only get the root element of the BST:
MyWordSet bst = new MyWordSet();
T bst = new T("one");
T bst = new T("two");
T bst = new T("three");
T bst = new T("four");
T bst = new T("five");
T bst = new T("six");
bst.add(w1);
bst.add(w2);
bst.add(w3);
bst.add(w4);
bst.add(w5);
bst.add(w6);
Iterator<T> it = bst.iterator();
while (it.hasNext())
{
System.out.println(it.next());
}
So the output is:
one
one
one
one
one
one
So why does this method inside my Iterator not work for me to get to the whole tree? I really can't figure out what is wrong here and why it only prints out one when it should go down the tree.
You simply do not update the current_node.
The equivalent of current_node = node is missing.
Well, after having changed the code, here revised answer:
import java.util.Iterator;
import java.util.Stack;
/**
*
* #author jk
*/
public class BSTIterator<T> implements Iterator<T> {
public static final class BST<T> {
private BST<T> left;
private BST<T> right;
private T word;
private BST(T word) {
this.word = word;
}
}
private final Stack<BST<T>> stackBST = new Stack<>();
public BSTIterator(final BST<T> root) {
// push all most left entries of the tree to the stack
BST<T> currBST = root;
while (currBST != null) {
stackBST.push(currBST);
currBST = currBST.left;
}
}
#Override
public boolean hasNext() {
return !stackBST.isEmpty();
}
#Override
public T next() {
BST<T> currBST = stackBST.pop();
// check if we are on the most right entry
final boolean notMostRightEntry = currBST.right != null;
if (notMostRightEntry) {
// take next right entry
BST<T> nextBST = currBST.right;
while (nextBST != null) {
// push this next right entry on the stack
stackBST.push(nextBST);
nextBST = nextBST.left;
}
}
return currBST.word;
}
public static void main(String[] args) {
BST<Integer> root = new BST<>(20);
root.left = new BST<>(5);
root.right = new BST<>(30);
root.left.right = new BST<>(10);
root.right.left = new BST<>(25);
root.right.right = new BST<>(40);
root.right.left = new BST<>(35);
root.right.left.left = new BST<>(32);
for (Iterator<Integer> bstIt = new BSTIterator<>(root); bstIt.hasNext();) {
System.out.println("val: " + bstIt.next());
}
}
}
I am making a boolean method that Deletes an element from the binary tree,
Returns true if the element is deleted successfully
, and Returns false if the element is not in the tree. The issue that I am having is that for some reason it is not deleting the node sometimes. I just want to know if I am doing anything wrong, thanks in advance.
here is my code:
public boolean delete(E e) {
BSTDelete<E> d = new BSTDelete<E>();
boolean deleted = d.delete(e, root);
if (deleted)
size -= 1;
return deleted;
}
public class BSTDelete<E extends Comparable<E>> {
public boolean delete(E e, TreeNode<E> root) {
if (root == null) {
return false;
}
if (e == root.element) {
if (root.right == null && root.left == null) {
root = null;
} else if (root.right == null) {
root = root.left;
} else if (root.left == null) {
root = root.right;
} else
root.element = minValue(root.left);
delete(root.element, root.left);
// Delete the inorder successor
} else if (e.compareTo(root.element) < 0) {
delete(e, root.left);
} else {
delete(e, root.right);
}
return true;
}
E minValue(TreeNode<E> root) {
E minv = root.element;
while (root.right != null) {
minv = root.right.element;
root = root.right;
}
return minv;
}
}
here is a test that keeps failing. The second assertEquals says that i.next() is "Beatrice" and not "Carl"
BST <String>b = new BST<String>();
b.insert("Arthur");
b.insert("Beatrice");
b.insert("Carl");
b.insert("Dagmar");
b.delete("Beatrice");
Iterator <String> i = b.iterator();
assertEquals(i.next(), "Arthur");
assertEquals(i.next(), "Carl");
assertEquals(i.next(), "Dagmar");
}
and here is my BSTInorderIterator class:
public class BSTInorderIterator<E extends Comparable<E>> implements
java.util.Iterator<E> {
int current = 0;
ArrayList<E> list = new ArrayList<E>();
private TreeNode<E> root;
public BSTInorderIterator(TreeNode<E> root) {
list = new ArrayList<E>();
inorder(root);
}
/** Inorder traversal from the root */
public void inorder() {
inorder(root);
}
/** Inorder traversal from a subtree */
public void inorder(TreeNode<E> root) {
if (root.left != null)
inorder(root.left);
list.add(root.element);
if (root.right != null)
inorder(root.right);
}
#Override
/** More elements for traversing? */
public boolean hasNext() {
return current < list.size();
}
#Override
/** Get the current element and move to the next */
public E next() {
return list.get(current++);
}
#Override
/** Remove the current element */
public void remove() {
// to do: make this work correctly
}
The delete method inside the class BSTDelete is a recursive method, however you're never returning the recursive method calls. Therefore your delete method will only ever return false when you call it with a like d.delete(e, root) where root is null.
For example even though delete(e, root.left) might return false because root.left is null your original method call will return true since you don't return the result of delete(e, root.left).
To fix this add return when you're calling the method recursively, this might only be a partial fix to your issue:
public boolean delete(E e, TreeNode<E> root) {
if (root == null) {
return false;
}
if (e == root.element) {
if (root.right == null && root.left == null) {
root = null;
} else if (root.right == null) {
root = root.left;
} else if (root.left == null) {
root = root.right;
} else
root.element = minValue(root.left);
return delete(root.element, root.left);
// Delete the inorder successor
} else if (e.compareTo(root.element) < 0) {
return delete(e, root.left);
} else {
return delete(e, root.right);
}
return true;
}
I have some problems with java(Dobly Linked List). i must add first node before last node. at first tried to build it, but not works. hier is my dobly linked list:
public class DoublyLinkedList<T>
{
private Element<T> first, last;
private int size;
public DoublyLinkedList()
{
first = last = null;
size = 0;
}
public int size()
{
return size;
}
public boolean isEmpty()
{
return size == 0;
}
// --- hier is Problem!!! I have changed just hier. ---
public void apply( T o ) {
Element<T> e = new Element<T>(o);
Element<T> current = first;
Element<T> save = first;
for(int i = 0; i < size; i++){
current = current.getNext();
}
current.connectAsPrevious(e);
e.connectAsNext(save);
size++;
}
// --- bekannte Methoden ---
public void add( T content )
{
Element<T> e = new Element<T>( content );
if ( isEmpty() )
{
first = last = e;
}
else
{
last.connectAsNext( e );
last = e;
}
size++;
}
public void showAll()
{
Element<T> current = first;
while ( current != null )
{
if ( current.getContent() != null )
{
System.out.print( current.getContent().toString() );
if ( current != last )
{
System.out.print(", ");
}
}
current = current.getNext();
}
System.out.println();
}
// --- weitere Methoden zum Testen ---
public void build( T[] elems )
{
for ( T e : elems ) { add( e ); }
}
public String toString()
{
String result = "";
Element current = first;
while ( current != null )
{
result += current.getContent().toString();
if ( current != last )
{
result += ", ";
}
current = current.getNext();
}
return result;
}
// Element
private static class Element<E>
{
private E content;
private Element<E> previous, next;
public Element( E c )
{
content = c;
previous = next = null;
}
public E getContent()
{
return content;
}
public void setContent( E c )
{
content = c;
}
public boolean hasNext()
{
return next != null;
}
public Element<E> getNext()
{
return next;
}
public void disconnectNext()
{
if ( hasNext() )
{
next.previous = null;
next = null;
}
}
public void connectAsNext( Element<E> e)
{
disconnectNext();
next = e;
if ( e != null )
{
e.disconnectPrevious();
e.previous = this;
}
}
public boolean hasPrevious()
{
return previous != null;
}
public Element<E> getPrevious()
{
return previous;
}
public void disconnectPrevious()
{
if ( hasPrevious() )
{
previous.next = null;
previous = null;
}
}
public void connectAsPrevious( Element<E> e )
{
disconnectPrevious();
previous = e;
if ( e != null )
{
e.disconnectNext();
e.next = this;
}
}
}
}
I think i must add whileloop. because if size 0 is, it stops on it and comes error NullPointerException. sorry for my bad english.
The reason you get a NullPointerException is that if you have an empty list then current is null (because it's assigned the value of first which is null) and current.connectAsPrevious will throw the exception.
Without knowing what the method is supposed to do it's difficult to suggest an alternative. However you can avoid the exception by putting if (current != null) before current.connectAsPrevious.
If it is supposed to add the item before the last item in the list (rather than as the last item) then you should just use your last reference rather than iterating through the list from the start:
e.connectAsNext(last);
e.connectAsPrevious(last.getPrevious());
last.connectAsPrevious(e);
I am stuck at the logic as for how to generate a tree when a string input is provided . Such as when i have a input of following form -
(1 (2 (3) (4)) (5 (6) ())
Representing tree will be like so -
1
/ \
2 5
/ \ /\
3 4 6 ()
I can build tree from usual like tree.add(data) and then looking for the new node to be self added by judging if its greater or smaller than parent node . But i am not able to understand how to implement how to store above the above mention string in binary data structure form.
Here's what i have tried so far -
public class BinaryTree {
static Node root;
public static void levelorder(Node<?> n) {
Queue<Node<?>> nodequeue = new LinkedList<Node<?>>();
if (n != null)
nodequeue.add(n);
while (!nodequeue.isEmpty()) {
Node<?> next = nodequeue.remove();
System.out.print(next.data + " ");
if (next.getLeft() != null) {
nodequeue.add(next.getLeft());
}
if (next.getRight() != null) {
nodequeue.add(next.getRight());
}
}
}
private static String[] breakString(String elements) {
int indexOfOpenBracket = elements.indexOf("(");
int indexOfLastBracket = elements.lastIndexOf(")");
String removedPString = elements.substring(indexOfOpenBracket + 1,
indexOfLastBracket);
String[] breakRemovedPString = removedPString.split(" ");
if (breakRemovedPString[1].contains("(")) {
add(breakRemovedPString[0], breakRemovedPString[1], breakRemovedPString[2]);
}
return breakRemovedPString;
}
static void add(String parent, String leftString, String rightString) {
Node<String> nodeToAdd = new Node<String>(parent);
if (root == null) {
root = nodeToAdd;
root.left = new Node<String>(leftString);
root.right = new Node<String>(rightString);
} else {
}
}
public static void main(final String[] args) {
String treeString = "(1 (2) (3))";
breakString(treeString);
levelorder(root);
System.out.println();
}
}
Please suggest some implementation for this problem.
This is a classical parsing problem. The simplest approach is probably recursive descent. Here is a grammar for the tree language:
T -> ( number T T )
| ( number )
| ()
To turn this into a parser, we can go through a formal transformation to LL(1) form and then code. I'll let you read up on that and show what results.
package treereader;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Reader;
enum Token { LPAREN, RPAREN, NUMBER, EOF, ERROR };
class Scanner {
final Reader in;
final char [] buf = new char[1];
final StringBuilder token = new StringBuilder();
private static final char EOF_MARK = Character.MIN_VALUE;
Scanner(Reader in) {
this.in = in;
read();
}
final void read() {
try {
if (in.read(buf) < 1) {
buf[0] = EOF_MARK;
}
} catch (IOException ex) {
System.err.println("i/o error");
buf[0] = EOF_MARK;
}
}
Token getNext() {
while (Character.isWhitespace(buf[0])) {
read();
}
if (Character.isDigit(buf[0])) {
token.setLength(0);
do {
token.append(buf[0]);
read();
} while (Character.isDigit(buf[0]));
return Token.NUMBER;
}
if (buf[0] == '(') {
read();
return Token.LPAREN;
}
if (buf[0] == ')') {
read();
return Token.RPAREN;
}
if (buf[0] == EOF_MARK) {
return Token.EOF;
}
return Token.ERROR;
}
String getString() {
return token.toString();
}
}
class Node {
public void print(PrintStream out) {
out.print("()");
}
}
class UnaryNode extends Node {
int val;
public UnaryNode(int val) {
this.val = val;
}
#Override
public void print(PrintStream out) {
out.print("(" + val + ")");
}
}
class BinaryNode extends Node {
int val;
Node left, right;
public BinaryNode(int val, Node left, Node right) {
this.val = val;
this.left = left;
this.right = right;
}
#Override
public void print(PrintStream out) {
out.print("(" + val + " ");
left.print(out);
out.print(' ');
right.print(out);
out.print(')');
}
}
class Parser {
final Scanner scanner;
Token lookAhead;
Parser(Reader in) {
scanner = new Scanner(in);
lookAhead = scanner.getNext();
}
void advance() {
lookAhead = scanner.getNext();
}
void match(Token token) throws IOException {
if (lookAhead == token) {
advance();
} else {
throw new IOException("Expected " + token + ", found " + lookAhead);
}
}
Node parse() throws IOException {
Node tree;
match(Token.LPAREN);
if (lookAhead == Token.NUMBER) {
int val = Integer.valueOf(scanner.getString());
advance();
if (lookAhead == Token.LPAREN) {
Node left = parse();
Node right = parse();
tree = new BinaryNode(val, left, right);
} else {
tree = new UnaryNode(val);
}
} else {
tree = new Node();
}
match(Token.RPAREN);
return tree;
}
}
public class TreeReader {
public static void main(String[] args) {
try {
Parser parser = new Parser(new BufferedReader(new FileReader(new File(args[0]))));
Node tree = parser.parse();
tree.print(System.out);
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
}