二叉树 前序 中序 后序遍历的递归,非递归Python实现

前言

马上网易游戏面试,为了不重蹈覆辙,最近复习了下二叉树 前序 中序 后序遍历的递归和非递归的Python实现方法。在这里做个记录。

代码

class Node(object):
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


# 前序 递归
def pre_order_recur(root):
    if not root:
        return
    print(root.val)
    pre_order_recur(root.left)
    pre_order_recur(root.right)


# 中序 递归
def in_order_recur(root):
    if not root:
        return
    in_order_recur(root.left)
    print(root.val)
    in_order_recur(root.right)


# 后序 递归
def post_order_recur(root):
    if not root:
        return
    post_order_recur(root.left)
    post_order_recur(root.right)
    print(root.val)


# 前序 非递归
def pre_order_none_recur(root):
    if not root:
        return
    stack = [root]
    while stack:
        cur = stack.pop()
        print(cur.val)
        if cur.right:
            stack.append(cur.right)
        if cur.left:
            stack.append(cur.left)


# 中序 非递归
def in_order_none_recur(root):
    if not root:
        return
    stack = []
    while stack or root:
        if root:
            stack.append(root)
            root = root.left
        else:
            root = stack.pop()
            print(root.val)
            root = root.right


# 后序 非递归
def post_order_none_recur(root):
    if not root:
        return
    stack = []
    mark_node = None
    while stack or root:
        if root:
            stack.append(root)
            root = root.left
        elif stack[-1].right != mark_node:
            root = stack[-1].right
            mark_node = None
        else:
            mark_node = stack.pop()
            print(mark_node.val)


if __name__ == '__main__':
    root = Node(1, Node(2, Node(4), Node(5, Node(7))), Node(3, Node(6)))
    print('前序递归的结果:'), pre_order_recur(root)
    print('前序非递归的结果:'), pre_order_none_recur(root)
    print('中序递归的结果:'), in_order_recur(root)
    print('中序非递归的结果:'), in_order_none_recur(root)
    print('后序递归的结果:'), post_order_recur(root)
    print('后序非递归的结果:'), post_order_none_recur(root)

测试用二叉树的结构

二叉树结构

运行结果

运行结果

Github地址

代码文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值