Create Expression Tree
Expression tree is a binary tree in which each internal node corresponds to operator and each leaf node corresponds to operand.
Solution:
- Fist convert infix to postfix
- Iterate postfix expression with stack
Algorithm
- Create stack
- Iterate expression string from start to end
- If
currentCharacter is operand
then- Create Binary Tree Node with this operand
stack.push(node)
- Else
operand1 = stack.pop
operand2 = stack.pop
- create node with currentCharacter
node.left = operand2
node.right = operand1
stack.push(node)
return stack.pop
Latest Source Code:
Github: ExpressionTreeCreator.java
Output:
Infix: A + B * C + D Expression Tree + / \ / \ / \ / \ + D / \ / \ A * / \ B C Infix: (A + B) * (C + D) Expression Tree * / \ / \ + + / \ / \ A B C D Infix: A * B + C * D Expression Tree + / \ / \ * * / \ / \ A B C D Infix: A + B + C + D Expression Tree + / \ / \ / \ / \ + D / \ / \ + C / \ A B