1. 程式人生 > >二叉樹(1)-----遍歷

二叉樹(1)-----遍歷

not nor tree tle pri 遞歸 分享 idt image

一、前序遍歷:

遞歸方式:

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] 

技術分享圖片

技術分享圖片

二叉樹(1)-----遍歷