1. 程式人生 > >【演算法 in python | 樹】二叉樹遍歷

【演算法 in python | 樹】二叉樹遍歷

二叉樹深度優先遍歷:先序遍歷,中序遍歷,後序遍歷的遞迴與非遞迴。

二叉樹廣度優先遍歷:層次遍歷。

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

#遞迴前序
def preTran(head):
    if head is not None:
        print(head.val)
        preTran(head.left)
        preTran(head.right)

#遞迴中序
def midTran(head):
    if head is not None:
        midTran(head.left)
        print(head.val)
        midTran(head.right)

#遞迴後序
def postTran(head):
    if head is not None:
        postTran(head.left)
        postTran(head.right)
        print(head.val)

#非遞迴前序
def preTranStack(head):
    if head is None:
        return
    p = head
    stack = []
    while p is not None or len(stack) > 0:
        if p is not None:
            print(p.val)
            stack.append(p)
            p = p.left
        else:
            p = stack.pop()
            p = p.right

#非遞迴中序
def midTranStack(head):
    if head is None:
        return
    p = head
    stack = []
    while p is not None or len(stack) > 0:
        if p is not None:
            stack.append(p)
            p = p.left
        else:
            p = stack.pop()
            print(p.val)
            p = p.right

#非遞迴後序
def postTranStack(head):
    if head is None:
        return
    cur = head
    pre = None
    stack = [cur]
    while len(stack) > 0:
        cur = stack[-1]
        if (cur.left is None and cur.right is None) or (pre == cur.left) or (pre == cur.right):
            cur = stack.pop()
            print(cur.val)
            pre = cur
        else:
            if cur.right is not None:
                stack.append(cur.right)
            if cur.left is not None:
                stack.append(cur.left)

#廣度優先,or層次遍歷
def BFS(head):
    p = head
    queue = [p]
    while len(queue) > 0:
        p = queue.pop(0)
        print(p.val)
        if p.left is not None:
            queue.append(p.left)
        if p.right is not None:
            queue.append(p.right)