Build Binary Expression Tree From Infix Expression — LeetCode 1597 Python Solution

HardLeetCode PremiumStackTreeStringBinary Tree
Problem
#1597
Pattern
Stack
Reading time
2 min

The problem

A binary expression tree is a kind of binary tree used to represent arithmetic expressions. Each node of a binary expression tree has either zero or two children.

Example

Input
s = "3*4-2*5"
Output
[-,*,*,3,4,2,5]
Explanation
The tree above is the only valid tree whose inorder traversal produces s.

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1597. Build Binary Expression Tree From Infix Expression is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1597. Build Binary Expression Tree From Infix Expression?
LeetCode 1597. Build Binary Expression Tree From Infix Expression is rated Hard on LeetCode.
What is the time complexity of LeetCode 1597. Build Binary Expression Tree From Infix Expression?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1597. Build Binary Expression Tree From Infix Expression?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1597. Build Binary Expression Tree From Infix Expression cover?
LeetCode 1597. Build Binary Expression Tree From Infix Expression is tagged Stack, Tree, String and Binary Tree on LeetCode.
Is LeetCode 1597. Build Binary Expression Tree From Infix Expression a premium problem?
Yes. LeetCode 1597. Build Binary Expression Tree From Infix Expression is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview