python实现基本算法

class Node(object):
    """创建节点类"""
    def __init__(self, elem=-1, lchild=None, rchild=None):
        self.elem = elem
        self.lchild = lchild
        self.rchild = rchild
"""就是每次将树中的节点依次取出来,放入队列,判断"""

class Tree(object):
    """创建树类"""
    def __init__(self, root=None):
        self.root = root

    def add(self, elem):
        """为树添加节点"""
        node = Node(elem)
        # 如果树是空的,则对根节点赋值
        if self.root == None:
            self.root = node
        else:
            queue = []
            queue.append(self.root)
            #当队列中不为空时
            while queue:
                #弹出队列的第一个元素
                cur = queue.pop(0)
                if cur.lchild == None:
                    cur.lchild = node
                    return
                elif cur.rchild == None:
                    cur.rchild = node
                    return
                else:
                    # 如果左右子树都不为空,加入队列继续判断
                    queue.append(cur.lchild)
                    queue.append(cur.rchild)
    """广度优先"""
    def width_circle(self):
        if self.root is None:
            return
        queue = []
        queue.append(self.root)
        while queue:
            cur = queue.pop(0)
            print(cur.elem)
            if cur.lchild is not None:
                queue.append(cur.lchild)
            if cur.rchild is not None:
                queue.append(cur.rchild)
    """先序"""
    def first_circle(self,root):
        if root is None:
            return
        print(root.elem,end=" ")
        self.first_circle(root.lchild)
        self.first_circle(root.rchild)



    """中序"""
    def middle_circle(self,root):
        if root is None:
            return
        self.middle_circle(root.lchild)
        print(root.elem,end=" ")
        self.middle_circle(root.rchild)
    """后序"""
    def post_circle(self, root):
        if root is None:
            return
        self.post_circle(root.lchild)
        self.post_circle(root.rchild)
        print(root.elem,end=" ")

if __name__ == '__main__':
    tree = Tree()
    tree.add(1)
    tree.add(2)
    tree.add(3)
    tree.add(4)
    tree.add(5)
    tree.first_circle(tree.root)
    print("")
    tree.middle_circle(tree.root)
    print("")
    tree.post_circle(tree.root)

你可能感兴趣的:(python实现基本算法)