A very good problem that tests your fundamental knowledge of how trees work. The algorithm is pretty straightforward, until you come across a leaf node, just keep track of all node’s values visited in the form of a number (or a string). Once you reach a leaf, return the number stored, and call the function recursively on other nodes.
Code:
Python3
Big O Analysis
-
Runtime
The runtime complexity here is
O(N)
as since we would visit all nodes atleast once. -
Memory
The memory usage is
O(N)
, since the tree is recursive, we would use the implicit call stack.
— A