Update bt_preorder.py

This commit is contained in:
bt3gl 2023-08-08 14:21:03 -07:00 committed by GitHub
parent 5eba7a1a80
commit a42c13186c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -8,4 +8,20 @@ def preorder(root) -> list:
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