So my goal is turn some sort of expression into a postfix expression (check), and then convert that expression into a binary tree. Here is my main class
public class ConvertIntoTree
{
public static void main(String[] args)
{
// Create a new InfixToPostfix expression from input
InfixtoPostfix mystack = new InfixtoPostfix(15);
System.out.println("Type in an expression like (1+2)*(3+4)/(12-5) //No spaces ");
Scanner scan = new Scanner(System.in);
String str = scan.next();
System.out.println("The Expression you have typed in infix form :\n"+str);
System.out.println("The Expression in Postfix is :\n"+mystack.InToPost(str));
ExpressionTree expressionTree = new ExpressionTree(str);
expressionTree.createExpressionTree();
//expressionTree.prefix();
System.out.println("The Expression I want");
expressionTree.infix();
}
}
and here is my expression tree class
class ExpressionTree {
private final String postfix;
private TreeNode root;
/**
* Takes in a valid postfix expression and later its used to construct the expression tree.
* The posfix expression, if invalid, leads to invalid results
*
* #param postfix the postfix expression.
*/
public ExpressionTree(String postfix) {
if (postfix == null) { throw new NullPointerException("The posfix should not be null"); }
if (postfix.length() == 0) { throw new IllegalArgumentException("The postfix should not be empty"); }
this.postfix = postfix;
}
private static class TreeNode {
TreeNode left;
char ch;
TreeNode right;
TreeNode(TreeNode left, char ch, TreeNode right) {
this.left = left;
this.ch = ch;
this.right = right;
}
}
private boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
/**
* Constructs an expression tree, using the postfix expression
*/
public void createExpressionTree() {
final Stack<TreeNode> nodes = new Stack<TreeNode>();
for (int i = 0; i < postfix.length(); i++) {
char ch = postfix.charAt(i);
if (isOperator(ch)) {
TreeNode rightNode = nodes.pop();
TreeNode leftNode = nodes.pop();
nodes.push(new TreeNode(leftNode, ch, rightNode));
} else {
nodes.add(new TreeNode(null, ch, null));
}
}
root = nodes.pop();
}
/**
* Returns the prefix notation
*
* #return the prefix notation
*/
public String prefix() {
if (root == null) {
throw new NoSuchElementException("The root is empty, the tree has not yet been constructed.");
}
final StringBuilder prefix = new StringBuilder();
preOrder(root, prefix);
return prefix.toString();
}
private void preOrder(TreeNode node, StringBuilder prefix) {
if (node != null) {
prefix.append(node.ch);
preOrder(node.left, prefix);
preOrder(node.right, prefix);
}
}
/**
* Returns the infix expression
*
* #return the string of infix.
*/
public String infix() {
if (root == null) {
throw new NoSuchElementException("The root is empty, the tree has not yet been constructed.");
}
final StringBuilder infix = new StringBuilder();
inOrder(root, infix);
return infix.toString();
}
private void inOrder(TreeNode node, StringBuilder infix) {
if (node != null) {
inOrder(node.left, infix);
infix.append(node.ch);
inOrder(node.right, infix);
}
}
}
After I run expressionTree.infix();, nothing. Obviously I'm doing something wrong. Any ideas or help, thanks.
After a little tinkering, the main issue was using expressionTree2.infix()
instead of System.out.println(expressionTree2.infix());
Related
Given a String such as this one, (((!D!)B!)A((!F(!H!))C(!G!))) with no white space. How would you build a binary tree?
I am supposed to implement a constructor and build it with an inoder traversal. This String would output
Any help/tips would be very appreciated!!!
Try this.
static Node parse(String input) {
return new Object() {
final int length = input.length();
int index = 0;
int ch = get();
int get() { return ch = index < length ? input.charAt(index++) : -1; }
Node node() {
if (ch == '!') {
get();
return null;
} else if (ch == '(') {
get();
Node left = node();
char data = (char)ch;
get();
Node right = node();
if (ch != ')')
throw new RuntimeException("')' expected");
get();
return new Node(left, data, right);
} else
throw new RuntimeException("'!' or '(' expected");
}
Node parse() {
Node node = node();
if (ch != -1)
throw new RuntimeException("extra string: " + input.substring(index - 1));
return node;
}
}.parse();
}
And
public static void main(String[] args) {
String input = "(((!D!)B!)A((!F(!H!))C(!G!)))";
Node root = parse(input);
System.out.println(root);
}
output:
Node[left=Node[left=Node[left=null, data=D, right=null], data=B, right=null], data=A, right=Node[left=Node[left=null, data=F, right=Node[left=null, data=H, right=null]], data=C, right=Node[left=null, data=G, right=null]]]
you can parse using recursion:
public BinaryTree(String t) {
this.root = parse(new StringReader(t));
}
private static Node parse(StringReader reader) {
char c = (char)reader.read();
if (c == '!')
return null;
if (c == '(') {
Node left = parse(reader);
char data = (char)reader.read();
Node right = parse(reader);
if (reader.read() != ')')
throw new IllegalArgumentException();
return new Node(left, data, right);
}
throw new IllegalArgumentException();
}
I am finishing up an expression tree program that takes in a postfix and gives the answer and the orginal equation back in infix form. I started working on about 6 months ago and had an issue I couldn't figure out. It works fine if the numbers are smaller than 9. For instance, 2 5 * 4 - prints out The infix: (2*5-4) 6.0 works fine. Something like 10 2 * prints out 20.0 but prints out The infix: (0*2) which isn't right. The big problem is that if a number is bigger than 9 it doesn't read that number in properly which messes up the conversion to infix. I am not sure how to fix this problem exactly. Below is my class and tester class:
import java.util.NoSuchElementException;
import java.util.Stack;
public class ExpressionTree
{
private final String postfix;
private TreeNode root;
/**
* Takes in a valid postfix expression and its used to construct the expression tree.
*/
public ExpressionTree(String postfix)
{
if (postfix == null) { throw new NullPointerException("The posfix should not be null"); }
if (postfix.length() == 0) { throw new IllegalArgumentException("The postfix should not be empty"); }
this.postfix = postfix;
}
private static class TreeNode
{
TreeNode left;
char ch;
TreeNode right;
TreeNode(TreeNode left, char ch, TreeNode right) {
this.left = left;
this.ch = ch;
this.right = right;
}
}
/**
* Checks to see if it is an Operator
*/
private boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
/**
* Constructs an expression tree, using the postfix expression
*/
public void createExpressionTree()
{
final Stack<TreeNode> nodes = new Stack<TreeNode>();
for (int i = 0; i < postfix.length(); i++)
{
char ch = postfix.charAt(i);
if (isOperator(ch))
{
TreeNode rightNode = nodes.pop();
TreeNode leftNode = nodes.pop();
nodes.push(new TreeNode(leftNode, ch, rightNode));
}
else if (!Character.isWhitespace(ch))
{
nodes.add(new TreeNode(null, ch, null));
}
}
root = nodes.pop();
}
/**
* Returns the infix expression
*
* #return the string of infix.
*/
public String infix()
{
if (root == null)
{
throw new NoSuchElementException("The root is empty, the tree has not yet been constructed.");
}
final StringBuilder infix = new StringBuilder();
inOrder(root, infix);
return infix.toString();
}
private void inOrder(TreeNode node, StringBuilder infix)
{
if (node != null) {
inOrder(node.left, infix);
infix.append(node.ch);
inOrder(node.right, infix);
}
}
public Double evaluate(String postfix)
{
Stack<Double> s = new Stack<Double>();
char[] chars = postfix.toCharArray();
int N = chars.length;
for(int i = 0; i < N; i++)
{
char ch = chars[i];
if(isOperator(ch))
{
switch(ch)
{
case '+': s.push(s.pop() + s.pop()); break;
case '*': s.push(s.pop() * s.pop()); break;
case '-': s.push(-s.pop() + s.pop()); break;
case '/': s.push(1 / s.pop() * s.pop()); break;
}
}
else if(Character.isDigit(ch))
{
s.push(0.0);
while (Character.isDigit(chars[i]))
s.push(10.0 * s.pop() + (chars[i++] - '0'));
}
}
return s.pop();
}
}
And the tester:
import java.util.Scanner;
public class ExpressionTester
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String line = null;
while(true)
{
System.out.println("");
String pf = sc.nextLine();
if (pf.isEmpty())
{
break;
}
ExpressionTree eT = new ExpressionTree(pf);
eT.createExpressionTree();
System.out.println("The infix: " + "(" + eT.infix() + ")" );
System.out.println(eT.evaluate(pf));
}
}
}
I have been working on this program to take in a postfix expression, calculate and print out its answer, and also convert it to infix expression. I have gotten the calculation part of it to work. For instance, if I enter 2 2 +(accounting for the spacing) it gives me 4. However, for the infix part of it it prints out 2+. I then tried it just doing it without any spacing. I put in 22+. The postfix did not work, but the infix printed out properly. So I am not sure how to fix this part of it. Here is my code.
import java.util.NoSuchElementException;
import java.util.Stack;
public class ExpressionTree
{
private final String postfix;
private TreeNode root;
/**
* Takes in a valid postfix expression and later its used to construct the expression tree.
* The posfix expression, if invalid, leads to invalid results
*
* #param postfix the postfix expression.
*/
public ExpressionTree(String postfix)
{
if (postfix == null) { throw new NullPointerException("The posfix should not be null"); }
if (postfix.length() == 0) { throw new IllegalArgumentException("The postfix should not be empty"); }
this.postfix = postfix;
}
private static class TreeNode
{
TreeNode left;
char ch;
TreeNode right;
TreeNode(TreeNode left, char ch, TreeNode right) {
this.left = left;
this.ch = ch;
this.right = right;
}
}
private boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
/**
* Constructs an expression tree, using the postfix expression
*/
public void createExpressionTree()
{
final Stack<TreeNode> nodes = new Stack<TreeNode>();
for (int i = 0; i < postfix.length(); i++)
{
char ch = postfix.charAt(i);
if (isOperator(ch))
{
TreeNode rightNode = nodes.pop();
TreeNode leftNode = nodes.pop();
nodes.push(new TreeNode(leftNode, ch, rightNode));
} else
{
nodes.add(new TreeNode(null, ch, null));
}
}
root = nodes.pop();
}
/**
* Returns the infix expression
*
* #return the string of infix.
*/
public String infix()
{
if (root == null)
{
throw new NoSuchElementException("The root is empty, the tree has not yet been constructed.");
}
final StringBuilder infix = new StringBuilder();
inOrder(root, infix);
return infix.toString();
}
private void inOrder(TreeNode node, StringBuilder infix) {
if (node != null) {
inOrder(node.left, infix);
infix.append(node.ch);
inOrder(node.right, infix);
}
}
public Double evaluate(String postfix)
{
Stack<Double> s = new Stack<Double>();
char[] chars = postfix.toCharArray();
int N = chars.length;
for(int i = 0; i < N; i++)
{
char ch = chars[i];
if(isOperator(ch))
{
switch(ch)
{
case '+': s.push(s.pop() + s.pop()); break;
case '*': s.push(s.pop() * s.pop()); break;
case '-': s.push(-s.pop() + s.pop()); break;
case '/': s.push(1 / s.pop() * s.pop()); break;
}
}
else if(Character.isDigit(ch))
{
s.push(0.0);
while (Character.isDigit(chars[i]))
s.push(10.0 * s.pop() + (chars[i++] - '0'));
}
}
return s.pop();
}
}
And here is my tester:
import java.util.Scanner;
public class ExpressionTester
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
while(true)
{
System.out.println("");
String pf = sc.nextLine();
ExpressionTree eT = new ExpressionTree(pf);
eT.createExpressionTree();
System.out.println("The infix: " + eT.infix() );
System.out.println(eT.evaluate(pf));
}
}
}
Any help would be greatly appreciated, as I really do not know how to fix this issue, and I am so close to finishing it.
if (isOperator(ch))
{
TreeNode rightNode = nodes.pop();
TreeNode leftNode = nodes.pop();
nodes.push(new TreeNode(leftNode, ch, rightNode));
}
else
{
nodes.add(new TreeNode(null, ch, null));
}
You're putting whitespace nodes into the tree. Try this:
if (isOperator(ch))
{
TreeNode rightNode = nodes.pop();
TreeNode leftNode = nodes.pop();
nodes.push(new TreeNode(leftNode, ch, rightNode));
}
else if (!Character.isWhitespace(ch))
{
nodes.add(new TreeNode(null, ch, null));
}
I'm writing a program that asks the user for a postfix expression, and then outputs the result to the expression. I am attempting to do this using a Singly Linked List, and using the Adapter Pattern to create a stack.
The code for the SinglyLinkedList class, the LinkedStack class, and the Stack implementation are all straight out of a Data Structures book that I own. So the SinglyLinkedListTest class is the only one that has my own code in it (and has errors).
I've written a program that simply uses a stack to evaluate a postfix expression before, but I'm getting confused this time with the extra classes included.
I'm sure I have a ton of errors, but the most obvious ones to me are in my SinglyLinkedListTest class, every time I push a value onto the stack. I know the issue is that I am attempting to push Objects and characters onto the stack instead of the arguments that match push(E e), but I don't know how to alter my code to make this work.
Any suggestions or input would be greatly appreciated.
Here is my Stack Implementation:
package PostFix;
public interface Stack<E>
{
int size();
boolean isEmpty();
void push(E e);
E pop();
}
Here is my LinkedStack class:
package PostFix;
public class LinkedStack <E> implements Stack<E>
{
private SinglyLinkedList<E> list = new SinglyLinkedList<>();
public LinkedStack()
{
}
public int size()
{
return list.size();
}
public boolean isEmpty()
{
return list.isEmpty();
}
public void push(E e)
{
list.addFirst(e);
}
public E pop()
{
return list.removeFirst();
}
}
Here is my SinglyLinkedList class:
package PostFix;
public class SinglyLinkedList<E>
{
private static class Node<E>
{
private E element;
private Node<E> next;
public Node(E e, Node<E> n)
{
element = e;
next = n;
}
public E getElement()
{
return element;
}
public Node<E> getNext()
{
return next;
}
}
private Node<E> head = null;
private Node<E> tail = null;
private int size = 0;
public SinglyLinkedList()
{
}
public int size()
{
return size;
}
public boolean isEmpty()
{
return size == 0;
}
public void addFirst(E e)
{
head = new Node<>(e, head);
if (size == 0)
{
tail = head;
}
size++;
}
public E removeFirst()
{
if (isEmpty())
{
return null;
}
E answer = head.getElement();
head = head.getNext();
size--;
if (size == 0)
{
tail = null;
}
return answer;
}
}
Here is my final SinglyLinkedListTest class:
package PostFix;
import java.util.Scanner;
public class SinglyLinkedListTest
{
public static void main(String[] args)
{
Double num1, num2, answer;
char c;
Stack<Double> stack = new LinkedStack<>();
Scanner input = new Scanner(System.in);
System.out.println("Enter the expression you would like to evaluate: ");
String someString = input.nextLine();
for (int index = 0; index < someString.length(); index++)
{
c = someString.charAt(index);
if (Character.isDigit(c))
{
stack.push((double)Character.digit(c, 10));
}
else if (c == '+')
{
num2 = stack.pop();
num1 = stack.pop();
answer = num1+num2;
stack.push(answer);
}
else if (c == '-')
{
num2 = stack.pop();
num1 = stack.pop();
answer = num1-num2;
stack.push(answer);
}
else if (c == '*')
{
num2 = stack.pop();
num1 = stack.pop();
answer = num1*num2;
stack.push(answer);
}
else if (c == '/')
{
num2 = stack.pop();
num1 = stack.pop();
answer = num1/num2;
stack.push(answer);
}
}
System.out.println("The result is: " + stack.pop());
}
}
Stack<String> buffer = new LinkedStack<>();
Poor name: call it stack.
You've declared it as Stack<String> but you're pushing chars:
buffer.push(someString.charAt(index));
and Objects:
buffer.push(answer);
and popping ints:
num1 = buffer.pop();
You are never either pushing or popping strings.
Just make up your mind. You should be pushing and popping ints, or longs, or doubles, or BigDecimals, depending on what precision you need.
EDIT
buffer.push((double)c);
is invalid. You're pushing the ASCII value, not the numeric value it corresponds to. You need
buffer.push((double)Character.digit(c, 10));
You also need an else after each if block: if the character is a digit, it won't be a +, and if it's a + it won't be a -, etc.
I have a project which is to “Start with the tree.java program (Listing 8.1) and modify it to create a binary
tree from a string of letters (like A, B, and so on) entered by the user. Each
letter will be displayed in its own node. Construct the tree so that all the nodes
that contain letters are leaves. Parent nodes can contain some non-letter
symbol like +. Make sure that every parent node has exactly two children.
Don’t worry if the tree is unbalanced.” The book gives us a hint on how to begin. “One way to begin is by making an array of trees. (A group of unconnected trees
is called a forest.) Take each letter typed by the user and put it in a node. Take
each of these nodes and put it in a tree, where it will be the root. Now put all
these one-node trees in the array. Start by making a new tree with + at the root
and two of the one-node trees as its children. Then keep adding one-node trees
from the array to this larger tree. Don’t worry if it’s an unbalanced tree.”
import java.io.*;
import java.util.*;
class Node
{
public String iData; // data item (key)
public Node leftChild; // this node’s left child
public Node rightChild; // this node’s right child
public void displayNode() // display ourself
{
System.out.print('{');
System.out.print(iData);
System.out.print("} ");
}
} // end class Node
class Tree
{
private Node root; // first node of tree
public void setNode(Node newNode)
{root = newNode;}
public Node getNode()
{return root;}
// -------------------------------------------------------------
public Tree() // constructor
{ root = null; } // no nodes in tree yet
// -------------------------------------------------------------
public void traverse(int traverseType)
{
switch(traverseType)
{
case 1: System.out.print("nPreorder traversal: ");
preOrder(root);
break;
case 2: System.out.print("nInorder traversal: ");
inOrder(root);
break;
case 3: System.out.print("nPostorder traversal: ");
postOrder(root);
break;
}
System.out.println();
}
private void preOrder(Node localRoot)
{
if(localRoot != null)
{
System.out.print(localRoot.iData + " ");
preOrder(localRoot.leftChild);
preOrder(localRoot.rightChild);
}
}
// -------------------------------------------------------------
private void inOrder(Node localRoot)
{
if(localRoot != null)
{
inOrder(localRoot.leftChild);
System.out.print(localRoot.iData + " ");
inOrder(localRoot.rightChild);
}
}
// -------------------------------------------------------------
private void postOrder(Node localRoot)
{
if(localRoot != null)
{
postOrder(localRoot.leftChild);
postOrder(localRoot.rightChild);
System.out.print(localRoot.iData + " ");
}
}
// -------------------------------------------------------------
public void displayTree()
{
Stack globalStack = new Stack();
globalStack.push(root);
int nBlanks = 32;
boolean isRowEmpty = false;
System.out.println(
"......................................................");
while(isRowEmpty==false)
{
Stack localStack = new Stack();
isRowEmpty = true;
for(int j=0; j<nBlanks; j++)
System.out.print(' ');
while(globalStack.isEmpty()==false)
{
Node temp = (Node)globalStack.pop();
if(temp != null)
{
System.out.print(temp.iData);
localStack.push(temp.leftChild);
localStack.push(temp.rightChild);
if(temp.leftChild != null ||
temp.rightChild != null)
isRowEmpty = false;
}
else
{
System.out.print("--");
localStack.push(null);
localStack.push(null);
}
for(int j=0; j<nBlanks*2-2; j++)
System.out.print(' ');
} // end while globalStack not empty
System.out.println();
nBlanks /= 2;
while(localStack.isEmpty()==false)
globalStack.push( localStack.pop() );
} // end while isRowEmpty is false
System.out.println(
"......................................................");
} // end displayTree()
// -------------------------------------------------------------
}
public class Leaves
{
//function used to enter the single node trees into a larger tree
public static void enterLetters(Node localRoot, Tree[] nodeTree, int i)
{
if(localRoot != null && i == nodeTree.length)
{
if(nodeTree.length == i - 1)
{
localRoot.leftChild = nodeTree[i].getNode();
localRoot.rightChild = nodeTree[i + 1].getNode();
enterLetters(localRoot.leftChild, nodeTree, i + 1);
}
else
{
Node plusNode = new Node();
plusNode.iData = "+";
localRoot.leftChild = plusNode;
localRoot.rightChild = nodeTree[i].getNode();
enterLetters(localRoot.leftChild, nodeTree, i + 1);
}
}
}
public static void main(String[] args)
{
Tree[] forest = new Tree[10];
Scanner sc = new Scanner(System.in);
for(int i = 0; i < 10; i++)
{
String letter;
forest[i] = new Tree();
System.out.println("Enter a letter: ");
letter = sc.nextLine();
Node newNode = new Node();
newNode.iData = letter;
forest[i].setNode(newNode);
}
Tree letterTree = new Tree();
Node firstNode = new Node();
firstNode.iData = "+";
letterTree.setNode(firstNode);
enterLetters(letterTree.getNode(), forest, 0);
letterTree.displayTree();
}
}
My problem is trying to get the array of single node trees into the larger tree. I tried making a recursive function but when I display the larger tree it only shows the first node and it is as if the function enterLeaves never did it’s job.
This can't be correct:
public static void enterLetters(Node localRoot, Tree[] nodeTree, int i) {
if (localRoot != null && i == nodeTree.length) {
if (nodeTree.length == i - 1) {
localRoot.leftChild = nodeTree[i].getNode();
localRoot.rightChild = nodeTree[i + 1].getNode();
enterLetters(localRoot.leftChild, nodeTree, i + 1);
} else {
Node plusNode = new Node();
plusNode.iData = "+";
localRoot.leftChild = plusNode;
localRoot.rightChild = nodeTree[i].getNode();
enterLetters(localRoot.leftChild, nodeTree, i + 1);
}
}
}
When you enter this method: localRoot != null, i == 0, and nodeTree.length==10
So the if statement is failing. I am guess the if statement should read:
if (localRoot != null && i < nodeTree.length)
Also, I am pretty sure your second if statement is incorrect also; I believe it should be.
if (nodeTree.length-2 == i) {
localRoot.leftChild = nodeTree[i].getNode();
localRoot.rightChild = nodeTree[i + 1].getNode();
return;
}
Instead of:
if (nodeTree.length == i - 1) {
localRoot.leftChild = nodeTree[i].getNode();
localRoot.rightChild = nodeTree[i + 1].getNode();
enterLetters(localRoot.leftChild, nodeTree, i + 1);
}
You want to stop when you have two Nodes left to process (nodeTree.length-2 == i) and after you do that you should return instead of entering the remaining letters.
Here's what I came up with that works:
Node.java
/** Represents a node in a binary tree data structure */
public class Node {
private char letter;
private Node leftChild;
private Node rightChild;
public Node(char letter) {
this.letter = letter;
}
public void setRightChild(Node rightChild) {
this.rightChild = rightChild;
}
public Node getRightChild() {
return rightChild;
}
public void setLeftChild(Node leftChild) {
this.leftChild = leftChild;
}
public Node getLeftChild() {
return leftChild;
}
/** Returns a String representation of this node. */
#Override
public String toString() {
return "" + letter;
}
}
Tree.java
import java.util.Stack;
/**
* A binary tree
*/
public class Tree {
private Node root;
public void setRoot(Node root) {
this.root = root;
}
public void addToLeft(Node node) {
root.setLeftChild(node);
}
public void addToRight(Node node) {
root.setRightChild(node);
}
public Node getRoot() {
return root;
}
public void displayTree() {
Stack<Node> globalStack = new Stack<>();
globalStack.push(root);
int nBlanks = 32;
boolean isRowEmpty = false;
System.out.println(
"......................................................");
while (!isRowEmpty) {
Stack<Node> localStack = new Stack<>();
isRowEmpty = true;
for (int j = 0; j < nBlanks; j++)
System.out.print(' ');
while (!globalStack.isEmpty()) {
Node temp = (Node) globalStack.pop();
if (temp != null) {
System.out.print(temp);
localStack.push(temp.getLeftChild());
localStack.push(temp.getRightChild());
if (temp.getLeftChild() != null ||
temp.getRightChild() != null)
isRowEmpty = false;
} else {
System.out.print("--");
localStack.push(null);
localStack.push(null);
}
for (int j = 0; j < nBlanks * 2 - 2; j++)
System.out.print(' ');
} // end while globalStack not empty
System.out.println();
nBlanks /= 2;
while (!localStack.isEmpty())
globalStack.push(localStack.pop());
} // end while isRowEmpty is false
System.out.println(
"......................................................");
}
}
Forest.java
/**
* A collection of OneNodeTrees combined together in one tree
*/
public class Forest {
private Tree[] forest;
private int forestIndex;
public Forest(int numTrees) {
forest = new Tree[numTrees];
forestIndex = 0;
}
public boolean add(Tree tree) {
if(forestIndex < forest.length) {
forest[forestIndex++] = tree;
return true;
} else {
return false;
}
}
public Tree createMainTree() {
Tree firstTree = new Tree();
firstTree.setRoot(new Node('+'));
firstTree.addToLeft(forest[0].getRoot());
firstTree.addToRight(forest[1].getRoot());
forest[1] = firstTree;
int mainTreeIndex = 0;
Tree tempTree;
for(mainTreeIndex = 2; mainTreeIndex < forest.length; mainTreeIndex++) {
tempTree = new Tree();
tempTree.setRoot(new Node('+'));
tempTree.addToLeft(forest[mainTreeIndex - 1].getRoot());
tempTree.addToRight(forest[mainTreeIndex].getRoot());
forest[mainTreeIndex] = tempTree;
}
return forest[mainTreeIndex - 1];
}
public static void main(String[] args) {
final int numberOfTrees = 6;
Forest forest = new Forest(numberOfTrees);
// Add characters starting from A which has ASCII value 65
int charLimit = 65 + numberOfTrees;
for(int i = 65; i < charLimit; i++) {
// Make new node.
Node newNode = new Node((char) i);
// Add that node to Tree as a root.
Tree newTree = new Tree();
newTree.setRoot(newNode);
// And add that one-node tree to forest(array)
forest.add(newTree);
}
Tree mainTree = forest.createMainTree();
mainTree.displayTree();
}
}
if(localRoot != null && i == nodeTree.length -1)
if you do not subtract one from node tree length you will have a duplicate child under the final parent node with 2 children