1. 程式人生 > >16_資料結構與演算法_遍歷樹(前序、中序、後序)_Python實現

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())