mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-06-18 11:59:33 -04:00
Update bt_preorder.py
This commit is contained in:
parent
5eba7a1a80
commit
a42c13186c
1 changed files with 16 additions and 0 deletions
|
@ -8,4 +8,20 @@ def preorder(root) -> list:
|
||||||
return []
|
return []
|
||||||
|
|
||||||
return [root.val] + preorder(root.left) + preorder(root.right)
|
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
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue