mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-29 12:16:14 -04:00
28 lines
592 B
Python
28 lines
592 B
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
# author: bt3gl
|
|
|
|
def preorder(root) -> list:
|
|
|
|
if root is None:
|
|
return []
|
|
|
|
return [root.val] + preorder(root.left) + preorder(root.right)
|
|
|
|
|
|
def preorder_iterative(root) -> list:
|
|
|
|
result = []
|
|
stack = [root]
|
|
|
|
while stack:
|
|
|
|
node = stack.pop()
|
|
|
|
if node:
|
|
result.append(node.val)
|
|
stack.append(node.right) # not the order
|
|
stack.append(node.left)
|
|
|
|
return result
|