shiroe

遍历方式

前序遍历

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

中序遍历

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

后序遍历

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

实现代码

三种遍历的外部函数方式

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

分类:

技术点:

相关文章:

  • 2021-11-01
  • 2021-07-06
  • 2021-08-03
  • 2021-07-16
  • 2021-05-25
  • 2021-04-25
  • 2021-06-24
  • 2021-10-09
猜你喜欢
  • 2021-06-13
  • 2021-08-21
  • 2022-12-23
  • 2021-06-10
  • 2022-12-23
  • 2022-02-25
  • 2022-02-08
相关资源
相似解决方案