mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-07 09:15:23 -04:00
add some fun tree playing
This commit is contained in:
parent
48720ada4d
commit
bb72bab679
6 changed files with 209 additions and 0 deletions
28
trees_and_graphs/preorder_transversal.py
Normal file
28
trees_and_graphs/preorder_transversal.py
Normal file
|
@ -0,0 +1,28 @@
|
|||
# recursive and iterative inorder traversal
|
||||
|
||||
def preorder_recursive(root: Optional[TreeNode]) -> list[int]:
|
||||
|
||||
if root == None:
|
||||
return []
|
||||
|
||||
return [root.val] + preorder_recursive(root.left) + preorder_recursive(root.right)
|
||||
|
||||
|
||||
def preorder_iterative(root: Optional[TreeNode]) -> 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
|
||||
|
Loading…
Add table
Add a link
Reference in a new issue