Input:
Output: A binary tree
Explanation:
The generated binary tree can have an arbitrary structure. For example:
1/ \
23/||\
4567This is just one of many possible trees that can be generated.
Let p be the probability that a node becomes a leaf (in this code, p = 1/2), and x be the probability that the entire tree is finite. The tree will be finite either if we terminate at the current node (probability p) or if we continue (probability 1-p) but both subtrees end up finite (probability x^2). Therefore, the equation is x = p + (1-p)x^2. Solving this yields x = min(p/(1-p), 1). Thus, for p = 1/2, the probability that the tree is finite is indeed 1. However, if p is lower, there is a positive probability that the tree will be infinite.
Generation:o(1) as the generate function returns the root node in constant time.
Evaluation: Each node evaluation is also o(1) as it involves a single probabilistic decision per node.
🧺 Space complexity: o(1) for generating the initial root node. However, in practice, the memory grows as more nodes are probabilistically created upon accessing children.