Leetcode # 589. N-ary Tree Preorder Traversal
- 2022.12.04
- Depth-First Search LeetCode
https://leetcode.com/problems/n-ary-tree-preorder-traversal/
Solution
Time Complexity: O(len(tree))
Space Complexity: O(len(tree))
(The input and output generally do not count towards the space complexity.)
class Solution:
def preorder(self, root: 'Node') -> List[int]:
stack = [root] if root is not None else []
preorder_traversal = []
while stack:
cur = stack.pop()
for node in cur.children[::-1]:
stack.append(node)
preorder_traversal.append(cur.val)
return preorder_traversal
Last Updated on 2023/08/16 by A1go