递归打印带有分支的树

2024-06-16 10:12:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Python递归地打印一棵树。由于某些原因,压痕不起作用(也许我现在太累了,看不到明显的缺陷)。下面是我正在使用的结构/类定义:

class Tree(object):
  def __init__(self, data):
    self.data = data
    self.branches = []

class Branch(object):
  def __init__(self, value):
    self.label = value
    self.node = None

如您所见,每棵树都有分支,它们有一个标签并指向另一棵树(这就是您在那里看到的node值)。下面是我如何打印出这棵树:

^{pr2}$

这给了我:

4
Somewhat: 
  Yes
Fuller: 
  3
Correct: 
  8
Caribbean: 
  2
Wrong: 
  Wrong
Correct: 
  Correct

Italian: 
  Wrong
Burger: 
  Correct

Wrong: 
  Wrong

Nothing: 
  Wrong

当它应该给我

4
Somewhat: 
  Correct
Fuller: 
  3
  Correct: 
    8
    Caribbean: 
      2
      Wrong: 
        Wrong
      Correct: 
        Correct
    Italian: 
      Wrong
    Burger: 
     Correct
  Wrong: 
    Wrong
Nothing: 
  Wrong

是什么导致我的代码有额外的换行而没有适当的缩进?在

更新

很肯定数据没问题。这是一个修改后的版本,显示它是可以的:

  def tree_string(self, indent):
    indentation = indent * " "
    result = str(self.data);
    if len(self.branches) > 0:
      result += "["
      for branch in self.branches:
        result += branch.label + ":" + branch.node.tree_string(indent + 2) + " "
      result += "]"
    return result

…这会产生输出

4[Somewhat:Correct Fuller:3[Correct:8[Caribbean:2[No:No Correct:Correct ] Italian:Wrong Burger:Correct ] Wrong:Wrong ] Nothing:Wrong ]

但是,由于某种原因,缩进值总是0或2。在


Tags: selfnodedatadefresultburgerindentfuller
1条回答
网友
1楼 · 发布于 2024-06-16 10:12:33

我觉得应该行得通:

class Tree(object):
  def __init__(self, data):
    self.data = data
    self.branches = []
  def __str__(self):
    return self.tree_string(0)

  def tree_string(self, indent):
    indentation = indent * " "
    result = indentation + str(self.data) + "\n";
    for branch in self.branches:
      result += indentation + branch.label + ": \n" + branch.node.tree_string(indent + 2)
    return result

class Branch(object):
  def __init__(self, value):
    self.label = value
    self.node = None

tree = Tree(4)
b1 = Branch('Somewhat')
b1.node = Tree('Yes')
b2 = Branch('Fuller')
b2.node = Tree(3)
tree.branches = [b1, b2]
b3 = Branch('Correct')
b3.node = Tree(8)
b2.node.branches = [b3]
print(tree)

收益率

^{pr2}$

相关问题 更多 >