mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-29 20:26:07 -04:00
Update bt_preorder_transversal.py
This commit is contained in:
parent
ba1a8755f0
commit
f7bc342551
@ -5,27 +5,25 @@
|
|||||||
|
|
||||||
def preorder_recursive(root: Optional[Node]) -> list[int]:
|
def preorder_recursive(root: Optional[Node]) -> list[int]:
|
||||||
|
|
||||||
if root == None:
|
if root is none None:
|
||||||
return []
|
return []
|
||||||
|
|
||||||
return [root.val] + preorder_recursive(root.left) + preorder_recursive(root.right)
|
return [root.val] + preorder_recursive(root.left) + preorder_recursive(root.right)
|
||||||
|
|
||||||
|
|
||||||
def preorder_iterative(root: Optional[Node]) -> list[int]:
|
def preorder_iterative(root) -> list:
|
||||||
|
|
||||||
result = []
|
result = []
|
||||||
stack = [root]
|
stack = [root]
|
||||||
|
|
||||||
while stack:
|
while stack:
|
||||||
|
|
||||||
current = stack.pop()
|
node = stack.pop()
|
||||||
result.append(current.val)
|
|
||||||
|
|
||||||
if current.right:
|
if node:
|
||||||
stack.append(current.right)
|
result.append(node.val)
|
||||||
|
stack.append(node.left)
|
||||||
if current.left:
|
stack.append(node.right)
|
||||||
stack.append(current.left)
|
|
||||||
|
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user