Python 二叉树的非递归遍历

二叉树类实现

class BinTNode:
    def __init__(self, dat, left = None, right = None):
        self.data = data
        self.left = left
        self.right = right

统计树中节点个数

def count_BinTNodes(t):
    if t is None:
        return 0
    else:
        return 1 + count_BinTNode(t.left) \
               + count_BinTNode(t.right)

求二叉树所有数值和

def sum_BinTNodes(t):
    if t is None:
        return 0
    else:
        return t.dat + sum_BinTNodes(t.left) \
               + sum_BinTNodes(t.right)

非递归的先根序遍历函数

def preorder_nonrec(t, proc):
    s = SStack()
    while t is not None or s.is_empty():
        while t is not None:        # 沿左分支下行
            proc(t.data)            # 先根序先处理根数据
            s.push(t.right)         # 右分支入栈
            t = t.left
        t = s.pop()


preorder_nonrec(tree, lambda x:print(x, end=" "))

通过生成器函数遍历
def preorder_elements(t):
    s = SStack()
    while i is not None or not s.is_empty():
        while t is not None:
            s.push(t.right)
            yield t.data
            t = t.left
        t = s.pop()

中序非递归遍历

def inorder_nonrec(t, proc):
    s = SStack()
    while t is not None or s.is_empty():
        while t is not None:
            s.push(t)
            t = t.left
        t = s.pop()
        proc(t.data)
        t = t.right

非递归的后根序遍历

def postorder_nonrec(t, proc):
    s = SStack()
    while t is not None or not s.is_empty():
        while t is not None:        # 下行循环, 直到栈顶的两子树空
            s.push(t)
            t = t.left if t.left is not None else t.right
        t = s.pop()                 # 栈顶是应访问节点
        proc(t.data)
        if not s.is_empty() and s.top().left == t:
            t = s.top().right       # 栈不为空且当前节点是栈顶的左子节点
        else:
            t = None                # 没有右子树或右子树遍历完毕, 强迫退栈

 

你可能感兴趣的:(算法,python)