Recursion and Trees
69 / 170Recursion and TreesLesson 2 of 13About 51 min
The structure is already recursive, so the code mirrors it. Almost every tree function is the same four lines.
Four questions, one shape. max_value returns the largest value, or None for an empty tree. count_leaves counts nodes with no children. all_positive reports whether every value is positive. mirror swaps every node's children in place and returns the root.
Tests
tree = T(1, T(2, T(4), T(5)), T(3))print(max_value(tree), max_value(None))print(count_leaves(tree), count_leaves(None), count_leaves(T(9)))print(all_positive(tree), all_positive(T(1, T(-2))), all_positive(None))print(to_list(mirror(T(1, T(2), T(3)))))Output
Run tests to see output.
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.