#1597
Hard Algorithms Build binary expression tree from infix expression
String Stack Tree Binary Tree
62.8% acceptance
Mar 31, 2026
271
49
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. Leaf nodes (nodes with 0 children) correspond to operands (numbers), and internal nodes (nodes with 2 children) correspond to the operators '+' (addition), '-' (subtraction), '*' (multiplication), and '/' (division).
For each internal node with operator o, the infix expression it represents is (A o B), where A is the expression the left subtree represents and B is the expression the right subtree represents.
You are given a string s, an infix expression containing operands, the operators described above, and parentheses '(' and ')'.
Return any valid binary expression tree, whose in-order traversal reproduces s after omitting the parenthesis from it.
Please note that order of operations applies in s. That is, expressions in parentheses are evaluated first, and multiplication and division happen before addition and subtraction.
Operands must also appear in the same order in both s and the in-order traversal of the tree.
Solution
C++
Time O(n²)
Space O(1)
/**
* Definition for a binary tree node.
* struct Node {
* char val;
* Node *left;
* Node *right;
* Node() : val(' '), left(nullptr), right(nullptr) {}
* Node(char x) : val(x), left(nullptr), right(nullptr) {}
* Node(char x, Node *left, Node *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
Node* expTree(string s) {
stack<Node*> nodes;
stack<char> ops;
auto apply = [&]() {
char op = ops.top(); ops.pop();
Node* right = nodes.top(); nodes.pop();
Node* left = nodes.top(); nodes.pop();
Node* node = new Node(op, left, right);
nodes.push(node);
};
auto precedence = [](char op) -> int {
if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
return 0;
};
for (char c : s) {
if (isdigit(c)) {
nodes.push(new Node(c));
} else if (c == '(') {
ops.push(c);
} else if (c == ')') {
while (ops.top() != '(') apply();
ops.pop();
} else {
while (!ops.empty() && ops.top() != '(' && precedence(ops.top()) >= precedence(c))
apply();
ops.push(c);
}
}
while (!ops.empty()) apply();
return nodes.top();
}
};