Recursion and Trees
72 / 170Recursion and TreesLesson 5 of 13About 39 min
The difference between an O(n squared) tree solution and an O(n) one is usually where the measuring happens.
Suppose every node must be checked against a property that depends on the height of its subtrees. The obvious code walks every node and, at each one, computes the heights from scratch.
That is the nested recursion from the last lesson, and here it is avoidable. Heights of a node's children are already computed while computing the height of the node itself, so recomputing them is pure waste.
This checks whether every node's two subtrees hold the same number of nodes. It is O(n squared). Click the line that causes the extra factor.
Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.