二叉树四种遍历Python实现

  最近很多朋友在找工作的时候遇到二叉树的问题,然后遇到前中后序三种深度遍历,以及广度优先遍历问题.我用Python写了一下.

# 3.6.1
# -*- coding:UTF-8 -*-

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

class TraversalBinaryTree:
    def preOrder(self, tree):
        if tree == None:
            return
        print(tree.data)
        self.preOrder(tree.left)
        self.preOrder(tree.right)

    def midOrder(self, tree):
        if tree == None:
            return
        self.midOrder(tree.left)
        print(tree.data)
        self.midOrder(tree.right)

    def postOrder(self, tree):
        if tree == None:
            return
        self.midOrder(tree.left)
        self.midOrder(tree.right)
        print(tree.data)

    def levelOrder(self, tree):
        if tree == None:
            return
        nodeQueue = []
        nodeQueue.append(tree)
        while nodeQueue:
            node = nodeQueue.pop(0);
            print(node.data)
            if node.left != None:
                nodeQueue.append(node.left)
            if node.right != None:
                nodeQueue.append(node.right)

以上的代码一次是前中后序遍历,以及广度优先遍历

0

发表评论

This site uses Akismet to reduce spam. Learn how your comment data is processed.