Reputation: 1087
I have to make a model of this arithmetical expression using a binary tree. Expression is a+b*c-b
Here's the model of my tree in Java
enum NodeType { NUMBER, OPERATOR } // Possible kinds of node.
class ExpNode { // A node in an expression tree.
NodeType kind; // Which type of node is this?
double number; // The value in a node of type NUMBER.
char op; // The operator in a node of type OPERATOR.
ExpNode left; // Pointers to subtrees,
ExpNode right; // in a node of type OPERATOR.
ExpNode( double val ) {
// Constructor for making a node of type NUMBER.
kind = NodeType.NUMBER;
number = val;
}
ExpNode( char op, ExpNode left, ExpNode right ) {
// Constructor for making a node of type OPERATOR.
kind = NodeType.OPERATOR;
this.op = op;
this.left = left;
this.right = right;
}
}
I don't know how to implement an insert method for adding a nodes. After that I will have to print the tree in console and change nodes for making this expression (a+b)*c-b Help me please, I'm not strong in Java
Upvotes: 2
Views: 1895
Reputation: 7824
First you need to keep track of the root
.
ExpNode root = new ExpNode(op, null, null);
To insert you need to find a node that has either left
or right
pointing to null
. Then create a new node and arrange the pointers.
Example to get you started:
ExpNode current = root;
while(current != null)
{
if(current.left == null)
{
ExpNode temp = new ExpNode(op, null, null);
current.left = temp;
break;
}
else if(current.right == null)
{
ExpNode temp = new ExpNode(op, null, null);
current.right = temp;
break;
}
else
current = current.left;
}
This code will you get started. Play with it, until you understand it, then you can tweak it to solve your homework. You should notice something peculiar happing on the left side of the tree.
Upvotes: 2