Python

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

2019-04-11  本文已影响130人  Python之战

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

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

两个子概念:

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

image

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

image

二叉树的实现

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

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)

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

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

image
上一篇 下一篇

猜你喜欢

热点阅读