二叉树(python实现)

二叉树是一种简单的树形结构,其每一个节点的分支节点数有0,1或2个。以下图T1,T2和T3是三棵二叉树。显然二叉树是一种递归的结构。node

 不包含任何节点的二叉树为空树,只有一个节点的二叉树称为单点树,一个节点的子节点的个数称为该节点的。若是每一个分支节点的度都为2,则称之为满二叉树。T4,T5就是两棵满二叉树。python

若是一棵二叉树,除最后一层外,其它层的节点都是满的,而最后一层节点在最左边连续排列,空位都在右边,这样的二叉树叫作彻底二叉树,如T六、T7所示。函数

如下代码定义了一个二叉树类spa

 

想要遍历一棵二叉树,有两种不一样的策略:深度优先遍历和宽度优先遍历。code

其中深度优先遍历策略有三种不一样的方式:blog

先根序遍历:按根节点、左子树、右子树的顺序遍历。递归

中根序遍历:按左子树、根节点、右子树的顺序遍历。队列

后根序遍历:按左子树、右子树、根节点的顺序遍历。element

#二叉树节点类
class BinTNode:
    def __init__(self,dat,left=None,right=None):
        self.data=dat
        self.left=left
        self.right=right

class BinTree:
    def __init__(self):
        self._root=None

    def is_empty(self):
        return self._root is None

    def root(self):
        return self._root

    def leftchild(self):
        return self._root.left

    def rightchild(self):
        return self._root.right

    def set_root(self,rootnode):
        self._root=rootnode

    def set_left(self,leftchild):
        self._root.left=leftchild

    def set_right(self,rightchild):
        self._root.right=rightchild

    def preorder_elements(self):
        t=self._root
        s = SStack()
        while t is not None or not s.is_empty():
            while t is not None:
                yield t.data
                s.push(t.right)
                t = t.left
            t = s.pop()

 

其中 preorder_elements()函数可遍历输出二叉树中的节点,实现了先根序遍历的方法。it

显然二叉树是是个递归结构,它的子树仍然可看作一个二叉树,所以二叉树许多方法均可以用递归方式实现。以下代码所示:

#二叉树节点类
class BinTNode:
    def __init__(self,dat,left=None,right=None):
        self.data=dat
        self.left=left
        self.right=right

#统计树中节点的个数
def count_BinTNode(t):
    if t is None:
        return 0
    else:
        return 1+count_BinTNode(t.left)+count_BinTNode(t.right)

#求二叉树里的全部数值之和
def sum_BinTNode(t):
    if t is None:
        return 0
    else:
        return t.dat+sum_BinTNode(t.left)+sum_BinTNode(t.right)

#递归方式的深度遍历二叉树(先根序),proc是具体的节点数据操做
def preorder(t,proc):
    if t is None:
        return
    proc(t.data)
    preorder(t.left,proc)
    preorder(t.right,proc)

 此外能够借助于队列实现二叉树的宽度优先遍历

#宽度优先遍历,proc是具体的节点数据操做
def levelorder(t,proc):
    qu=SQueue()
    qu.enqueue(t)
    while not qu.is_empty():
        n=qu.dequeue()
        if n is None:
            continue
        qu.enqueue(n.left)
        qu.enqueue(n.right)
        proc(n.data)