美文网首页
python 非递归实现二叉树前中后序遍历

python 非递归实现二叉树前中后序遍历

作者: ThompsonHen | 来源:发表于2021-04-07 10:37 被阅读0次
# 先序遍历
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