天天看点

python实现二叉树及其基本方法

什么是二叉树:每个节点最多有两个子树的树结构,通常子树被称作“左子树”(left subtree)和“右子树”(right subtree)。

二叉树具备以下数学性质:

  • 在二叉树的第i层上至多有2^(i-1)个结点(i>0)
  • 深度为k的二叉树至多有2^k - 1个结点(k>0)
  • 对于任意一棵二叉树,如果其叶结点数为N0,而度数为2的结点总数为N2,则N0=N2+1;
  • 具有n个结点的完全二叉树的深度必为 log2(n+1)
  • 对完全二叉树,若从上至下、从左至右编号,则编号为i 的结点,其左孩子编号必为2i,其右孩子编号必为2i+1;其双亲的编号必为i/2(i=1 时为根,除外)

两个子概念:

满二叉树:除最后一层无任何子节点外,每一层上的所有结点都有两个子结点二叉树

完全二叉树:设二叉树的深度为h,除第 h 层外,其它各层 (1~h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中在最左边,这就是完全二叉树。

二叉树的实现

二叉树由两个对象组成,一个是节点对象,一个是树对象

class Node:

    """节点类"""

    def __init__(self, elem, lchild=None, rchild=None):

        self.elem = elem

        self.lchild = lchild

        self.rchild = rchild


class Tree:

    """树类"""

    def __init__(self, root=None):

        self.root = root
           

接下来给这树添加基本方法:增加节点

class Node:

    """节点类"""

    def __init__(self, elem, lchild=None, rchild=None):

        self.elem = elem

        self.lchild = lchild

        self.rchild = rchild


class Tree:

    """树类"""

    def __init__(self, root=None):

        self._root = root


    def add(self, item):

        node = Node(item)

        if not self._root:

            self._root = node

            return

        queue = [self._root]

        while queue:

            cur = queue.pop(0)

            if not cur.lchild:

                cur.lchild = node

                return

            elif not cur.rchild:

                cur.rchild = node

                return

            else:

                queue.append(cur.rchild)

                queue.append(cur.lchild)
           

对二叉树节点的操作是通过列表存储节点的形式来操作,但是二叉树数据本身是通过链表的形式来存储,节点的操作一般使用递归函数。

二叉树的遍历又分为深度遍历和广度遍历,深度遍历还要分中序遍历/先序遍历/后序遍历,将在下一篇来给二叉树增加遍历方法。