二叉树(1)-----遍历

一、前序遍历:

递归方式:

def preorder(tree):
    if tree:
        print(tree.val)
        preorder(tree.getLeftChild())
        preorder(tree.getRightChild())

非递归方式:时间复杂度O(n),空间复杂度O(n)

def preOrder(head):
    if not head:
        return None
    res ,stack = [] , [head]
    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 inorder(tree):    
    if tree:
        inorder(tree.left)
        print(tree.val)
        inorder(tree.right)

非递归方式:

def InOrder(head):
    if not head:
        return None
    res ,stack = [] , []
    cur = head
    while stack or cur:
        if cur:
            stack.append(cur)
            cur = cur.left
        else:
            cur = stack.pop()
            res.append(cur.val)
            cur =cur.right
    return res

 三、后序遍历:

递归

def postorder(tree):
    if tree:
        postorder(tree.left)
        postorder(tree.right))
        print(tree.val)

非递归:

def PosOrder(head):
    if not head:
        return []
    s1 , s2 = [head] , []
    cur = head
    while s1:
        cur = s1.pop()
        s2.append(cur.val)
        if cur.left:
            s1.append(cur.left)
        if cur.right:
            s1.append(cur.right)
    return s2[::-1] 

 

猜你喜欢

转载自www.cnblogs.com/Lee-yl/p/9809835.html