[英]Why isn't the tree being printed?
我正在嘗試創建一個Tree
類,我首先創建一個樹節點類,然后開始制作樹模塊。 我嘗試創建的第一種方法是print_tree
。
我遍歷樹的策略是:
None
則中斷(這意味着我們回到了根節點)但它不起作用。 為什么?
class treeNode:
def __init__(self,data):
self.data = data
self.children = []
self.parent = None
self.nextSibling = None
self.level = 0
def add_children(self,*child):
for i in child:
i.parent = self
self.children.append(i)
self.children[-1].nextSibling = i.data
def level_func(self):
itr = self
count = 0
while itr:
count += 1
itr = itr.parent
self.level = count - 1
class Tree:
def __init__(self,root:treeNode):
self.root = root
def print_tree(self):
print(self.root.data)
kid = self.root.children[0]
while (kid != self.root):
kid.level_func()
print(" " * (3 * kid.level),kid.data)
if len(kid.children) == 0:
while kid.nextSibling is None or kid.parent is None:
kid = kid.parent
else:
kid = kid.nextSibling
else:
kid = kid.children[0]
parent = treeNode(1)
child = treeNode(2)
parent.add_children(child,treeNode(3),treeNode(4),treeNode(5))
grand = treeNode(6)
child.add_children(grand,treeNode(7))
tree1 = Tree(parent)
tree1.print_tree()
您應該讓節點通過遞歸處理遍歷。 要打印,請實現__repr__()
方法,以便您可以直接在樹節點上使用 print():
class treeNode:
...
# list of lines to print for this node and its descendants
def lines(self,indent="",indent2=""): # node indent, children indent
result = [indent+str(self.data)] # line for node data
for last,child in enumerate(self.children,1-len(self.children)):
lines=child.lines(indent2+"|__ ",indent2+["| "," "][last==0]))
result.extend(lines) # add descendant lines
return result
def __repr__(self):
return "\n".join(self.lines())
輸出:
parent = treeNode(1)
child = treeNode(2)
parent.add_children(child,treeNode(3),treeNode(4),treeNode(5))
grand = treeNode(6)
child.add_children(grand,treeNode(7))
parent.children[-1].add_children(treeNode(10))
tree1 = Tree(parent)
print(tree1.root)
1
|__ 2
| |__ 6
| |__ 7
|__ 3
|__ 4
|__ 5
|__ 10
print(child)
2
|__ 6
|__ 7
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.