This is a fundamental tree problem that requires us to collect the preorder traversal of a tree in a list and return it. A preorder traversal is a tree/graph traversal where you visit the first node (root in a case of a tree), and then it’s children.
Code:
Python
Big O Analysis
-
Runtime
The runtime complexity here is
O(N)
as since we would be visiting all the nodes in the tree. -
Memory
The memory usage is
O(1)
since we are not using any extra datastructure (usually the returning result array does not count, if it counts, then it’sO(N)
).
— A