Update and rename preorder_transversal.py to bt_preorder_transversal.py

This commit is contained in:
marina 2023-08-03 13:18:57 -07:00 committed by GitHub
parent 7520042ef9
commit 84b35ceaf3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -0,0 +1,31 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# author: bt3gl
def preorder_recursive(root: Optional[Node]) -> list[int]:
if root == None:
return []
return [root.val] + preorder_recursive(root.left) + preorder_recursive(root.right)
def preorder_iterative(root: Optional[Node]) -> list[int]:
result = []
stack = [root]
while stack:
current = stack.pop()
result.append(current.val)
if current.right:
stack.append(current.right)
if current.left:
stack.append(current.left)
return result