python二叉树实现

class Node(object):
    """元素节点"""
    def __init__(self, elem=None, 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,node):
        """添加元素"""

        if self.root is None:
            self.root = node
        else:
            li = []
            li.append(self.root)
            while li:
                cur = li.pop(0)
                if cur.lchild is None:
                    cur.lchild = node
                    return
                if cur.rchild is None:
                    cur.rchild = node
                    return
                li.append(cur.lchild)
                li.append(cur.rchild)

    def pre_order(self, root):
      """先序遍历"""
      if root == None:
          return
      print(root.elem)
      self.pre_order(root.lchild)
      self.pre_order(root.rchild)

    def mid_order(self, root):
        """中序遍历"""
        if root == None:
            return
        self.mid_order(root.lchild)
        print(root.elem)
        self.mid_order(root.rchild)

    def post_order(self, root):
        """后序遍历"""
        if root == None:
            return
        self.post_order(root.lchild)
        self.post_order(root.rchild)
        print(root.elem)

if __name__ == '__main__':
    tree = Tree()
    tree.add(Node("A"))
    tree.add(Node("B"))
    tree.add(Node("C"))
    tree.add(Node("D"))
    tree.add(Node("E"))
    tree.add(Node("F"))
    tree.add(Node("G"))
    # tree.pre_order(tree.root)
    # tree.mid_order(tree.root)
    tree.post_order(tree.root)
发布了82 篇原创文章 · 获赞 10 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/xin_yun_Jian/article/details/84001068