16_数据结构与算法_遍历树(前序、中序、后序)_Python实现

#Created By: Chen Da

#定义一个二叉树的类
class Binary_Tree(object):
    def __init__(self,root):
        self.key = root
        self.left_child = None
        self.right_child = None

    def insert_left(self,node):
        if self.left_child is None:
            self.left_child = Binary_Tree(node)
        else:
            tree_ = Binary_Tree(node)
            tree_.left_child = self.left_child
            self.left_child = tree_

    def insert_right(self,node):
        if self.right_child is None:
            self.right_child = Binary_Tree(node)
        else:
            tree_ = Binary_Tree(node)
            tree_.left_child = self.left_child
            self.left_child = tree_

    def get_left_child(self):
        return self.left_child

    def get_right_child(self):
        return self.right_child

    def get_root_val(self):
        return self.key

    def set_root(self,obj):
        self.key = obj


#二叉树的前序遍历(首先访问根节点,然后递归的对左子树进行前序遍历,接着递归的对右子树进行前序遍历)
#这里是采用的了外部函数的形式,也可以把previous_order()作为一个方法写到树的类中
def previous_order(tree):
    if tree != None:
        print(tree.get_root_val())
        previous_order(tree.get_left_child())
        previous_order(tree.get_right_child())

#二叉树的后序遍历(递归地对左子树进行后序遍历,然后递归地对右子树进行后序遍历,最后返回根节点)
def post_order(tree):
    if tree != None:
        post_order(tree.get_left_child())
        post_order(tree.get_right_child())
        print(tree.get_root_val())

#二叉树的中序遍历(递归的对左子树进行中序遍历,接着返回根节点,然后递归的对右子树进行中序遍历)
def inner_order(tree):
    if tree != None:
        inner_order(tree.get_left_child())
        print(tree.get_root_val())
        inner_order(tree.get_right_child())

猜你喜欢

转载自blog.csdn.net/PyDarren/article/details/83830740