python - 递归树遍历并将每个输出作为字符串python返回

标签 python algorithm tree binary-tree

基本上我有这个二叉树:

enter image description here

我想做的是遍历它,所以我得到一个 str 返回给我,它的值为 +BA。为了做到这一点,我有以下功能:

def order(root):

    if (root != None):
        root.visit() # this calls a binary tree function that just prints out root.data
        order(root.right)
        order(root.left)

这很好用,但我需要返回一个 str 而不是打印每个遍历。我尝试创建一个 str,并执行 str += root.visit(),但是每次都会重置,所以最后它没有用。如何返回包含所有遍历的字符串?

我尝试过的:

def order(root):
    rep = ""
    if (root != None):
        rep += root.visit()
        order(root.right)
        order(root.left)

    return rep

最佳答案

为了预序遍历二叉树,您应该遵循以下方案:

def traverse(node):
    rep = ""
    if node is not None:
        rep += node.visit()
        rep += traverse(node.right)
        rep += traverse(node.left)
    return rep

关于python - 递归树遍历并将每个输出作为字符串python返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42462931/

相关文章:

python - 如何在Python中向用户定义函数添加计数器?

python - 重写子类中的 __new__ 以创建特定的父类实例是一种反模式吗?

c# - 两个 BST 叶子之间的节点之和

python - 从上到下查找通过树(嵌套字典)的所有路径

java - Play 中使用 Hibernate 的菜单树!

javascript - Bokeh 嵌入在 Flask 中不起作用(Bokeh 未定义)

python - scipy 最小化函数的输入结构

javascript - 使用什么样的算法来创建 "linked network nodes"的这种视觉效果?

algorithm - 如何解决 Codeforces 的 Twisty Movement?

algorithm - 计算 Pi 的不同方法