二叉树的遍历python实现

二叉树的前,中,后,层次遍历

递归版本的前序遍历

def preOrderRecur(node):
    if not node:
        return
    print(node.val)
    preOrderRecur(node.left)
    preOrderRecur(node.right)

递归版本的中序遍历

def inOrderRecur(node):
    if not node:
        return
    inOrderRecur(node.left)
    print(node.val)
    inOrderRecur(node.right)

递归版本的后序遍历

def postOrderRecur(node):
    if not node:
        return
    postOrderRecur(node.left)
    postOrderRecur(node.right)
    print(node.val)

非递归版本的前序遍历

弹出即存,利用栈的特性优先遍历左子树

def preOrderStack(node):
    if not node:
        return
    stack = [node]
    res = []
    while stack:
        cur = stack.pop()
        res.append(cur.val)
        if cur.right:
            stack.append(cur.right)
        if cur.left:
            stack.append(cur.left)
    return res

非递归版本的中序遍历

def inOrderStack(node):
    if not node:
        return
    stack = []
    res = []
    cur = node
    while stack or cur:
        while cur:
            stack.append(cur)
            cur = cur.left
        cur = stack.pop()
        res.append(cur.val)
        cur = cur.right
    return res

非递归版本的后序遍历

def postOrderStack(node):
    if not node:
        return
    stack = [node]
    res = []
    while stack:
        cur = stack.pop()
        res.append(cur.val)
        if cur.left:
            stack.append(cur.left)
        if cur.right:
            stack.append(cur.right)
    return res[::-1]

层次遍历

def levelOrder(node):
    if not root:
        return
    queue = [node]
    res = []
    while queue:
        cur = queue.pop(0)
        res.append(cur.val)
        if cur.left:
            queue.append(cur.left)
        if cur.right:
            queue.append(cur.right)
    return res

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值