二叉树遍历(四种方式、迭代及递归的实现)

二叉树的常见遍历方式主要有前序,中序和后序,以及层次遍历(从上到下,从左到右)四种方法。

前、中、后遍历分别顺序如下:

分别通过递归和循环的方式实现(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)

猜你喜欢

转载自blog.csdn.net/Torero_lch/article/details/81951612