python 非递归实现二叉树前中后序遍历
2021-04-07 本文已影响0人
ThompsonHen
# 先序遍历
def pre_order(root):
res = []
stack = []
cur = root
while stack or cur:
while cur:
res.append(cur.val)
stack.append(cur)
cur = cur.left
top = stack.pop()
cur = top.right
# 中序遍历
def in_order(root):
res = []
stack = []
cur = root
while stack or cur:
while cur:
stack.append(cur)
cur = cur.left
top = stack.pop()
res.append(top.val)
cur = top.right
# 后序遍历
def post_order(root):
res = []
stack = []
cur = root
while stack or cur:
while cur:
res.append(cur.val)
stack.append(cur)
cur = cur.right
top = stack.pop()
cur = top.left
return res[::-1]