Magicsheet logo

Build Binary Expression Tree From Infix Expression

Hard
42.3%
Updated 6/1/2025

Asked by 2 Companies

Build Binary Expression Tree From Infix Expression

What is this problem about?

The "Build Binary Expression Tree From Infix Expression interview question" asks you to convert a standard mathematical expression (like 3+5×23 + 5 \times 2) into a tree structure. In this tree, internal nodes are operators and leaf nodes are operands. The tree must respect the standard order of operations (precedence). This is a foundational problem in compiler design and expression evaluation.

Why is this asked in interviews?

Companies like Snap and Amazon use the "Build Binary Expression Tree From Infix Expression coding problem" to evaluate a candidate's understanding of Tree and Stack data structures. It tests your ability to handle operator precedence and parentheses. It’s a significant step up from simply evaluating an expression, as you must maintain the hierarchical relationship between operations.

Algorithmic pattern used

This problem typically uses the Two-Stack (Shunting-Yard variation) or Monotonic Stack pattern.

  1. Operands Stack: Stores the nodes (leaves or subtrees) created so far.
  2. Operators Stack: Stores the symbols (+, -, *, /) and parentheses.
  3. Precedence Rule: When an operator comes in, if it has lower or equal precedence than the top of the operator stack, pop the operator, pop two nodes from the operand stack, create a new tree node with the operator as root, and push it back.
  4. Parentheses: '(' is pushed, and ')' triggers popping and node creation until '(' is found.

Example explanation

Expression: 3 + 5 * 2

  1. Read 3: Operand Stack [3].
  2. Read +: Operator Stack [+].
  3. Read 5: Operand Stack [3, 5].
  4. Read *: * has higher precedence than +. Push *. Operator Stack [+, *].
  5. Read 2: Operand Stack [3, 5, 2].
  6. End: Pop *, pop 5 and 2. Create node (5*2). Operand Stack [3, node(*)].
  7. Pop +, pop 3 and node(*). Create node 3 + (5*2).

Common mistakes candidates make

  • Precedence errors: Treating all operators with the same priority.
  • Pointer management: Not correctly linking the left and right children during node creation (order matters!).
  • Whitespace: Forgetting to handle or skip spaces in the input string.

Interview preparation tip

Master the Shunting-Yard algorithm. It is the standard way to handle "String interview pattern" problems involving math. Practice building the tree vs. evaluating the value to see the subtle differences in state management.

Similar Questions