Class MathExpressionTreeDepth
java.lang.Object
com.github.gbenroscience.parser.MathExpressionTreeDepth
Optimized Java class to compute the depth (height) of the abstract syntax tree (AST)
for a mathematical expression.
Features:
- Handles numbers (integers, decimals, scientific notation like 1.2e-3)
- Variables (e.g., x, varName_123)
- Binary operators: + - * / ^ (power, right-associative)
- Unary + and -
- Functions with any number of arguments (e.g., sin(x), max(a, b, c+ d))
- Parentheses for grouping
- No external libraries, single-pass O(n) parsing with zero heap allocations
(only recursion stack, which is bounded by expression complexity)
- Spaces are ignored
Tree depth definition:
- Leaf (number or variable) = 1
- Binary operator node = 1 + max(left depth, right depth)
- Function node = 1 + max(argument depths)
- Parentheses do not add extra depth (they are just grouping)
Example:
"2 + 3 * 4" -> depth 3 ((2 + (3 * 4)))
"-2^3" -> depth 3 (- (2 ^ 3))
"2^-3" -> depth 3 (2 ^ (-3))
"sin(2 + 3 * 4)" -> depth 4
"(1 + (2 + (3 + 4)))"-> depth 4
-
Nested Class Summary
Nested Classes -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic void
-
Constructor Details
-
MathExpressionTreeDepth
-
-
Method Details
-
calculate
-
main
-