# Evaluate Expression Tree

Table of Contents

Statement

BST Representation

tree
tree = -1
/ \
-2 -3
/ \ / \
-4 2 8 3
/ \
2 3

Solution Explanation

We are given a binary expression tree, where each leaf is a number and each internal node is an operator:

-1 β†’ add, -2 β†’ subtract, -3 β†’ divide, -4 β†’ multiply

To solve it, we evaluate the tree from the bottom to the top. If the node is a number, we return it. If the node is an operator, we first solve the left and right subtrees, and then we apply the correct math operation.

This is why we use recursion β€” each node depends on the result of its children.

⏱️ Time Complexity O(n).

We must visit every node one time to get the final result from the tree. So, if the tree has n nodes, we do n steps.

➑️ More nodes = more steps, in a straight line. That’s why it’s O(n).

πŸ’Ύ Space Complexity O(h).

h = the height of the tree (how many levels it has from top to bottom).

Because we use recursion, each recursive call is stored in memory until the operation finishes. The computer needs space for each β€œstep” in the path down the tree.

➑️ If the tree is tall, we use more memory. ➑️ If the tree is short, we use less memory.

That’s why it’s O(h).

Soluction

hello.py
// Define BST class
class BST {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
function evaluateTree(tree){
// If it's a positive number, return it
if(tree.value >=0 ) return tree.value
// Evaluate left and right sides
const leftValue = evaluateExpressionTree(tree.left)
const rightValue = evaluateExpressionTree(tree.right)
// Apply the operation
if (tree.value == -1)
return leftValue + rightValue
if (tree.value == -2)
return leftValue - rightValue
if (tree.value == -3)
return parseInt(leftValue / rightValue)
if(tree.value == -4)
return leftValue * rightValue
}
// Build tree
const root = new BST(-1);
root.left = new BST(-2);
root.right = new BST(-3);
root.left.left = new BST(-4);
root.left.right = new BST(2);
root.right.left = new BST(8);
root.right.right = new BST(3);
root.left.left.left = new BST(2);
root.left.left.right = new BST(3);
console.log(evaluateTree(root));
Next: LeetCode: node-depths
My avatar

Appreciate you reading. If you want more hacking write-ups, network labs, and code deep-dives, check out my other posts or connect via the social links in the footer.


LeetCode Series