To create a binary expression tree from an infix expression, you can follow these steps:
- Tokenization: Break the infix expression into individual tokens (operands, operators, parentheses, etc.).
- Conversion to Postfix: Convert the infix expression into its equivalent postfix notation using the shunting-yard algorithm or a similar method. This step ensures that the expression’s operator precedence is maintained.
- Construction of Expression Tree: Use the postfix expression to construct the binary expression tree recursively.
- Start with an empty stack.
- Iterate through each token in the postfix expression.
- If the token is an operand, create a leaf node for it and push it onto the stack.
- If the token is an operator, pop the top two nodes from the stack, create a new node with the operator as the root, and make the popped nodes its children. Push this new node onto the stack.
- Repeat until all tokens are processed.
- The final node remaining on the stack will be the root of the binary expression tree.
Now, let’s create the binary expression tree for the expression A+B*C:
- Infix expression: A+B*C
- Convert to postfix: ABC*+
- Construct expression tree:
- Start with an empty stack.
- Process each token from left to right.
- When encountering operands, push them onto the stack.
- When encountering operators:
- Pop the top two operands from the stack.
- Create a new node with the operator as the root, and make the popped operands its left and right children.
- Push this new node onto the stack.
- At the end, the root of the tree will be the only element left in the stack.
Steps:
- Token: A Stack: A
- Token: B Stack: A, B
- Token: C Stack: A, B, C
- Token: * Pop: C, B Create: * with left child B and right child C Stack: A, (B * C)
- Token: + Pop: (B * C), A Create: + with left child A and right child (B * C) Stack: (A + (B * C))
The final binary expression tree for the expression A+B*C:
Anup Maurya Changed status to publish April 13, 2024