mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-29 12:16:14 -04:00
Update bt_postorder.py
This commit is contained in:
parent
15d407b4ef
commit
ff3987dffc
@ -4,8 +4,34 @@
|
||||
|
||||
def postorder(root) -> list:
|
||||
|
||||
if root is None:
|
||||
if root is None:
|
||||
return []
|
||||
|
||||
return postorder(root.left) + postorder(root.right) + [root.val]
|
||||
return postorder(root.left) + postorder(root.right) + [root.val]
|
||||
|
||||
|
||||
def postorder_iterative(root) -> list:
|
||||
|
||||
stack, result = [], []
|
||||
node = root
|
||||
|
||||
while node or stack:
|
||||
|
||||
while node:
|
||||
if node.right:
|
||||
stack.append(node.right)
|
||||
stack.append(node)
|
||||
node = node.left
|
||||
|
||||
node = stack.pop()
|
||||
|
||||
if stack and node.right == stack[-1]:
|
||||
stack[-1] = node
|
||||
node = node.right
|
||||
|
||||
else:
|
||||
result.append(node.val)
|
||||
node = None
|
||||
|
||||
return result
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user