Building a binary tree
Author |
Message |
efus
|
Posted: Fri Nov 28, 2008 5:26 am Post subject: Building a binary tree |
|
|
Hi. I am working on a project where I convert postfix notation to infix and evaluateing it. This includes building an evaluations tree (binary tree). I get how to create nodes, but how do I get the whole tree?
This is the code I have so far:
code: |
import java.util.*;
import java.io.*;
import java.lang.*;
public class test {
public static void main (String args[]) {
Deque<Object> stack = new ArrayDeque<Object>();
String exsp = "2 2 * 3 + 11 8 - * 2 *";
String[] operators = {"-","+","*","/"};
StringTokenizer st = new StringTokenizer(exsp); // deler udtrykket i tokens
while (st.hasMoreTokens())
{
String T=st.nextToken();
for(int i = 0; i < 3; i++ )
{
if( T.equals( operators[i]))
{
Node n1 = new Node (stack.pop(),null,null);
Node n2 = new Node (stack.pop(),null,null);
Node p = new Node(T,n1,n2);
stack.push(T);
break;
}
else if( Character.isDigit(T.charAt(0)) ) //tjekker kun det forste symbol.
{
Node p = new Node(T, null, null);
stack.push(T);
break;
}
}
}
}
}
class Node
{
Object data;
Node leftChild;
Node rightChild;
public Node(Object D, Node L, Node R)
{
this.data = D;
this.leftChild = L;
this.rightChild = R;
}
public void inorder()
{
if( leftChild != null )
leftChild.inorder();
System.out.print( " " + data );
if( rightChild != null )
rightChild.inorder();
}
public Double eval ()
{
Double validated=0.1;
return validated;
}
public String infix()
{
String result = "";
return result;
}
}
|
|
|
|
|
|
|
Sponsor Sponsor
|
|
|
jernst
|
Posted: Fri Nov 28, 2008 10:08 am Post subject: Re: Building a binary tree |
|
|
A couple suggestions so far:
- Your "for loop": instead of hardcoding 3 into the loop you might want to consider using the size of the operators, in case you wish to add more operators later one
- Also when you are checking if the current token is an operator, you should maybe move the else if part out of the for loop, because otherwise for every operator you have it will also check if it is a digit. For example, say what you actually have is the last operator in the list. It will look for each of the first operators, plug check each time if it is a digit.
As for building the tree, you will want to keep track of a root node somewhere and then you need to figure out where to stick the children from there (I think you need to use one of the operators as the root and have the children as your digits as well as other operators as the roots of subtrees) But it also depends on the priority of the operation as well |
|
|
|
|
|
|
|