1. 程式人生 > >二叉樹遍歷(四種方式、迭代及遞迴的實現)

二叉樹遍歷(四種方式、迭代及遞迴的實現)

二叉樹的常見遍歷方式主要有前序,中序和後序,以及層次遍歷(從上到下,從左到右)四種方法。

前、中、後遍歷分別順序如下:

分別通過遞迴和迴圈的方式實現(Python):

# -*- coding:utf-8 -*-
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

def reConstructBinaryTree(pre, tin):
    # write code here
    if len(pre) == 0:
        return None
    if len(pre) == 1:
        return TreeNode(pre[0])
    else:
        node = TreeNode(pre[0])
        index = tin.index(pre[0])
        node.left = reConstructBinaryTree(pre[1:index + 1], tin[:index])
        node.right = reConstructBinaryTree(pre[index + 1:], tin[index + 1:])
    return node


def predigui(root):
    if root==None:
        return
    print(root.val)
    predigui(root.left)
    predigui(root.right)

def prexunhuan(root):
    if root==None:
        return
    node=root
    stack=[]
    while node or stack:
        while node:
            print(node.val)
            stack.append(node)
            node=node.left
        node=stack.pop()
        node=node.right
        pass

def indigui(root):
    if not root:
        return
    indigui(root.left)
    print(root.val)
    indigui(root.right)

def inxunhuan(root):
    if not root:
        return
    stack=[]
    node=root
    while stack or node:
        while node :
            stack.append(node)
            node=node.left
        node=stack.pop()
        print(node.val)
        node=node.right

def postdigui(root):
    if not root:
        return
    postdigui(root.left)
    postdigui(root.right)
    print(root.val)

def postxunhuan(root):
    if not root:
        return
    node=root
    stack=[]
    stack2=[]
    while node or stack:
        while node:
            stack.append(node)
            stack2.append(node)
            node=node.right
        node=stack.pop()
        node=node.left
    while stack2:
        print(stack2.pop().val)

if __name__=='__main__':
    root=reConstructBinaryTree([1,2,4,7,3,5,6,8],[4,7,2,1,5,3,8,6])
    #predigui(root)
    #prexunhuan(root)
    #indigui(root)
    #inxunhuan(root)
    #postdigui(root)
    postxunhuan(root)