python 非递归实现二叉树前中后序遍历
# 先序遍历
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]
本文标题:python 非递归实现二叉树前中后序遍历
本文链接:https://www.haomeiwen.com/subject/adelqltx.html
网友评论