树的遍历算法

树的遍历算法

树的前序遍历

递归的方式:

class TreeNode:
    def __init__(self,val):
        self.val=val
        self.left=None
        self.right=None
def preorder(root):
    if root==None:
        return
    print(root.val,end=' ')
    preorder(root.left)
    preorder(root.right)

非递归的方式:
思路:借助一个栈,当栈不为空时,从栈里面弹出一个节点,先把右节点压入栈,再把左节点压入栈
代码:

def preorder1(root):
    if not root:
        return
    stack=[root]
    while stack:
        p=stack.pop()
        print(p.val,end=' ')
        if p.right:
            stack.append(p.right)
        if p.left:
            stack.append(p.left)

树的中序遍历算法

递归的遍历方式:

def inorder(root):
    if not root:
        return
    inorder(root.left)
    print(root.val,end=' ')
    inorder(root.right)

非递归的遍历方式:
思路:当前节点不为空,压入栈,向左走,当前节点为空,从栈中拿出一个打印,向左走

def inorder1(root):
    if not root:
        return
    stack=[]
    while stack or root:
        if root!=None:
            stack.append(root)
            root=root.left
        else:
            root=stack.pop()
            print(root.val,end=' ')
            root=root.right

树的后序遍历算法

递归的遍历方式:

def postorder(root):
    if not root:return
    postorder(root.left)
    postorder(root.right)
    print(root.val,end=' ')

非递归的遍历方式
思路:在前序遍历中,借助一个栈,先压右,再压左,是中左右,在后序遍历中,先压右再压左,即中右左,然后再借助一个栈中反向弹出就变成后序遍历的顺序:左右中了
代码:

def postorder1(root):
    if not root:
        return
    stack=[root]
    s=[]
    while stack:
        root=stack.pop()
        s.append(root)
        if root.left:
            stack.append(root.left)
        if root.right:
            stack.append(root.right)
    while s:
        p=s.pop()
        print(p.val,end=' ')

二叉树按层遍历

按层遍历在一行打印出来

def level_order(root):
    queue=[root]
    while queue:
        root=queue.pop(0)
        print(root.val,end=' ')
        if root.left:
            queue.append(root.left)
        if root.right:
            queue.append(root.right)

按层遍历按层打印出来

def level_order1(root):
    cur_line=0
    queue=[[root,cur_line]]
    while queue:
        root,line=queue.pop(0)
        if line!=cur_line:
            print()
            cur_line=line
        print(root.val,end=' ')
        if root.left:
            queue.append([root.left,cur_line+1])
        if root.right:
            queue.append([root.right,cur_line+1])
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值