【数据结构与算法Python版学习笔记】树——树的遍历 Tree Traversals

遍历方式

前序遍历

在前序遍历中,先访问根节点,然后递归地前序遍历左子树,最后递归地前序遍历右子树。

中序遍历

在中序遍历中,先递归地中序遍历左子树,然后访问根节点,最后递归地中序遍历右子树。

后序遍历

在后序遍历中,我们先递归地后序遍历访问左子树和右子树,最后访问根节点

实现代码

三种遍历的外部函数方式

def preorder(tree):
    """前序遍历"""
    if tree:
        print(tree.getRootVal())
        preorder(tree.getLeftChild())
        preorder(tree.getRightChild())

def postorder(tree):
    """后序遍历"""
    if tree != None:
        postorder(tree.getLeftChild())
        postorder(tree.getRightChild())
        print(tree.getRootVal())

def inorder(tree):
    """中序遍历"""
    if tree != None:
        inorder(tree.getLeftChild())
        print(tree.getRootVal())
        inorder(tree.getRightChild())

BinaryTree类中实现前序遍历的方法

def preorder(self):
        print(self.key)
        if self.leftChild:
            self.leftChild.preorder()
        if self.rightChild:
            self.rightChild.preorder()

采用后序遍历法重写表达式求值代码


def evaluate(parseTree):
    opers = {
        '+': operator.add,
        '-': operator.sub,
        '*': operator.mul,
        '/': operator.truediv
    }
    # 缩小规模
    leftC = parseTree.getLeftChild()
    rightC = parseTree.getRightChild()

    if leftC and rightC:
        fn = opers[parseTree.getRootVal()]
        # 递归调用
        return fn(evaluate(leftC), evaluate(rightC))
    else:
        # 基本结束条件
        return parseTree.getRootVal()

# 后序遍历法
def postordereval(tree):
    opers = {
        '+': operator.add,
        '-': operator.sub,
        '*': operator.mul,
        '/': operator.truediv
    }
    res1 = None
    res2 = None
    if tree:
        res1 = postordereval(tree.getLeftChild())
        res2 = postordereval(tree.getRightChild())
        if res1 and res2:
            return opers[tree.getRootVal()](res1, res2)
        else:
            return tree.getRootVal()

中序遍历:生成全括号中缀表达式

def printTexp(tree):
    sVal = ''
    if tree:
        sVal = '('+printTexp(tree.getLeftChild())
        sVal = sVal+tree.getRootVal()
        sVal = sVal+printTexp(tree.getRightChild())+')'
    return sVal
posted @ 2021-04-22 14:15  砥才人  阅读(208)  评论(0编辑  收藏  举报