python学习(一)

二叉树(前、中、后序遍历)

class BinaryTree(object):
    def __init__(self,data):
        self.__left = None
        self.__right = None
        self.__data = data
    def __del__(self):
        del self.__data
    def add_left_node(self,data):
        if self.__left:
            print("Left node exist!")
        else:
            self.__left = BinaryTree(data)
            return self.__left
    def add_right_node(self,data):
        if self.__right:
            print("Right node exist!")
        else:
            self.__right = BinaryTree(data)
            return self.__right
    def show(self):
        print(self.__data)
    def pre_order(self):#前序遍历
        print(self.__data,end=" ")
        if self.__left:
            self.__left.pre_order()
        if self.__right:
            self.__right.pre_order()
    def in_order(self):#中序遍历
        if self.__left:
            self.__left.in_order()
        print(self.__data,end=" ")
        if self.__right:
            self.__right.in_order()
    def post_order(self):#后序遍历
        if self.__left:
            self.__left.post_order()
        if self.__right:
            self.__right.post_order()
        print(self.__data,end=" ")
if __name__ == "__main__":
    root = BinaryTree("root")
    a = root.add_left_node("A")
    b = root.add_right_node("B")
    c = a.add_right_node("C")
    d = b.add_left_node("D")
    e = b.add_right_node("E")
    root.show()
    root.pre_order()
    print("")
    root.in_order()
    print("")
    root.post_order()
阅读更多