Hello JPF,
I have just been introduced to trees, and for my assignment, I have to build an expression tree. I have the algorithm and idea down, but I'm not exactly sure where to start. So I have completed the code to change an infix notation to a postfix notation. I know that if I'll have to scan the postfix notation, token by token. If the token is an operand, I need to create a one-node tree and push it onto a stack. If the token is an operator, I have to pop off the two top trees from the stack and create a new tree with the operator as my root and the two operand trees as my children. I'm hoping that someone can look over my codes and help me start off. I have some codes that I have tried, but I'm getting a null error pointer. Anything would be greatly appreciated.
What I have so far:
public BinaryTree<String> buildExpressionTree() { String post=postfixx; StringTokenizer tokens = new StringTokenizer(post); while (tokens.hasMoreTokens()) { String nextToken = tokens.nextToken(); // Does it start with a digit? if (Character.isDigit(nextToken.charAt(0))) { // Get the integer value. BinaryTree<String> newTree = new BinaryTree<String>(nextToken,null,null); tree.push(newTree);[B] //I'm getting an error right here.[/B] } // Is it an operator? else if (isOperator(nextToken.charAt(0))) { BinaryTree<String> first=tree.pop(); BinaryTree<String> second=tree.pop(); BinaryTree<String> expression= new BinaryTree<String>(nextToken,first, second); eTree=expression; tree.push(expression); } } return eTree; }