Update bt_postorder.py

This commit is contained in:
bt3gl 2023-08-08 14:32:28 -07:00 committed by GitHub
parent 15d407b4ef
commit ff3987dffc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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