【问题标题】:Print contents of tree in level-order, using the eval function to read the input tree in python按级别顺序打印树的内容,使用eval函数读取python中的输入树
【发布时间】:2019-06-29 08:13:02
【问题描述】:

部分问题需要按级别顺序打印树,所以如果输入树是:

("hello", (("a", ()), ("b", (("cde", ()), ("fg", ()))))) 

那么输出应该是,

hello

a b

cde fg

* 注意:输入树可以有任意数量的子树 *

这里似乎很独特的是应该使用输入树,

tree = eval(input('Enter tree: '))

大多数类似的问题都倾向于使用 Node 类和/或队列组件,我没有发现它们对这个问题有帮助,而且我找不到任何使用 eval 函数进行输入的情况。

这是我目前所拥有的,

def level_order(node):
  label, children = node
  print(label)
  for child in children:
    level_order(child)

tree = eval(input('Enter tree: '))
level_order(tree)

我当前的程序能够打印内容,我认为这是预先遍历。如何让它按级别顺序打印?

【问题讨论】:

  • 你需要以广度优先的方式走树...

标签: python recursion tree tuples


【解决方案1】:

你需要先进行一次广度遍历

def level_order(*nodes):
    if not nodes: # base case
       return
    # all the labels and all the groups of chilren for this "level"
    labels,childrens = zip(*nodes)
    print("\t".join(labels))
    # flatten the list so instead of [[c1,c2],[c3,c4,c5,...]] we get [c1,c2,c3,...]
    flattened_children = [c for children in childrens for c in children]
    # call recursively
    level_order(*flattened_children)

level_order(("hello", (("a", ()), ("b", (("cde", ()), ("fg", ()))))) )

【讨论】:

  • 效果很好!谢谢!我唯一不明白的是星号是做什么的,即 *nodes 和 *flattened_children?
  • pls1,虽然我试图找到一些用于树解析/遍历的 bultin 库。你有这样的想法吗?
猜你喜欢
  • 1970-01-01
  • 2012-02-04
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-15
  • 2012-10-22
  • 1970-01-01
相关资源
最近更新 更多