So you want to build a random tree of OperatorNode
s, OperandNode
s and XNode
s? And you said you want the tree depth determinant to be determined?
Define a recursive function called buildRandomTree
or something similar. For the depth of the tree, one int
parameter must be used. If the depth parameter is 1, return a random leaf node (OperandNode or XNode). If the depth parameter is greater than 1, generate a random OperatorNode and make recursive calls to create the left and right subtrees (with a depth of 1 less than the current level).
Depending on what you want to do with the nodes, you will have to define other recursive functions. For example, you probably want to create textual representations of your expression trees. To do this, you can define toString()
for each of the node classes. ( OperatorNode.toString()
will need to call toString()
in the left and right subtrees.)
You might also want to evaluate expression trees (with given values ββfor variables). To do this, you can define another recursive function, possibly called evaluate()
. He will have to take one parameter, possibly Map
, which will give the variable values ββ(or "bindings") that you want to evaluate with the expression. (Right now, your expression trees can only contain one variable "x", but I think you can add more. If you are sure that you will use only one variable, then evaluate
can take one numeric argument for the value "x".)
Implementing evaluate
for your 3 node classes will be very simple. OperandNode
and VariableNode
will simply return the value directly; OperatorNode
will have to call evaluate
in the left and right subtrees, combine the values ββwith the appropriate operation, and then return the result.
source share