Could someone explain how to build a binary expression tree.
For example I have a string 2*(1+(2*1));
How to convert this into a binary expression tree.
*
| \
| \
2 +
|\
1 *
|\
2 1
Convert infix to postfix or prefix
The postfix input is: a b + c d e +**
Java Implementation
public Tree.TreeNode createExpressionTree(){
Iterator<Character>itr = postOrder.iterator();
Tree tree = new Tree();
NodeStack nodeStack = new NodeStack();
Tree.TreeNode node;
while (itr.hasNext()) {
Character c = itr.next();
if(!isDigit(c)){
node = tree.createNode(c);
node.right = nodeStack.pop();
node.left = nodeStack.pop();
nodeStack.push(node);
}else{
node = tree.creteNode(c);
nodeStack.push(node);
}
}
node = nodeStack.pop();
return node;
}
More info: http://en.wikipedia.org/wiki/Binary_expression_tree
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With