ADS
Algorithms and Data Structures
Loading...
Searching...
No Matches
ExpressionTree.h File Reference

The tree of an arithmetic expression (the parse tree), beyond the book: a binary tree [see BinaryTree.h] whose leaves are the operands, numbers or names of variables, and whose internal nodes are the binary operators +, -, *, / and ^ (the power), the left subtree being the left operand. More...

#include "ADS/Contract.h"
#include "ADS/stack/ArrayStack.h"
#include "ADS/tree/BinaryTree.h"
#include <cmath>
#include <map>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include "ADS/tree/impl/ExpressionTree.tpp"

Go to the source code of this file.

Namespaces

namespace  ADS

Functions

BinaryTree< std::string > * ADS::expressionTree (std::string_view e)
 the expression tree of the postfix expression \( e \), whose tokens are separated by spaces; the caller owns it
double ADS::evaluate (const BinaryTree< std::string > *t, const std::map< std::string, double > &env={})
 the value of the expression \( t \), with the variables valued by env; a leaf is a number, possibly signed (e.g., -3, +2.5, .5), or a variable
std::string ADS::prefixForm (const BinaryTree< std::string > *t)
 the prefix form of \( t \), each subtree in parentheses, by a previsit (section 5.6)
std::string ADS::infixForm (const BinaryTree< std::string > *t)
 the infix form of \( t \), fully parenthesized, by an invisit (section 5.6)

Detailed description

The tree of an arithmetic expression (the parse tree), beyond the book: a binary tree [see BinaryTree.h] whose leaves are the operands, numbers or names of variables, and whose internal nodes are the binary operators +, -, *, / and ^ (the power), the left subtree being the left operand.

  • expressionTree() builds it from the postfix form of the expression [see Expressions.h] with a stack of trees: an operand is pushed as a leaf, an operator pops its right and then its left subtree and pushes the new tree, in \( O( n ) \);
  • evaluate() computes its value by a postvisit, the values of the variables given by a dictionary;
  • prefixForm() writes it in prefix form, each subtree in parentheses, e.g., (*(/(3)(+(*(^(x)(2))(y))(*(3)(x))))(-(z)(1))) for \( ( 3 / ( x^2 y + 3 x ) ) ( z - 1 ) \), and infixForm() in infix form, fully parenthesized, by an invisit.

The contracts [see Contract.h]: the postfix expression is well formed, i.e., each operator finds two subtrees and one tree is left; evaluate() needs a value for each variable, and no division by 0. The functions are defined in ExpressionTree.tpp.

See also
A. Montresor, Algoritmi e Strutture Dati, 2025, sections 5.5 and 5.6, https://algoritmicamente.it/materiali/libro/capitoli/cap05.pdf
Author
Donato Meoli
Dipartimento di Informatica
Università di Pisa