# Evaluate Expression Tree
Table of Contents
Statement
BST Representation
tree = -1 / \ -2 -3 / \ / \ -4 2 8 3 / \ 2 3Solution 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
// Define BST classclass 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));