python 二叉树遍历

二叉树的前序遍历

递归

def preorder(root,res=[]):
    if not root:
        return 
    res.append(root.val)
    preorder(root.left,res)
    preorder(root.right,res)
    return res

迭代

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

二叉树的中序遍历

递归

def inorder(root,res=[]):
    if not root:
        return 
    inorder(root.left,res)
    res.append(root.val)
    inorder(root.right,res)
    return res

迭代

def inorder(root):
    stack=[]
    node=root
    res=[]
    while stack or node:
        while node:
            stack.append(node)
            node=node.left
        node=stack.pop()
        res.append(node.val)
        node=node.right
    return res

二叉树的后序遍历

递归

def laorder(root,res=[]):
    if not root:
        return 
    laorder(root.left,res)
    laorder(root.right,res)
    res.append(root.val)
    return res

迭代

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

二叉树的层次遍历

迭代

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

 转载自:https://blog.youkuaiyun.com/wenkenza5368/article/details/79573333

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值