【发布时间】:2020-07-09 05:10:58
【问题描述】:
class TreeNode:
def __init__(self, data):
self.data = data
self.children = []
self.parent = None
def get_level(self):
level = 0
p = self.parent
while p:
level += 1
p = p.parent
return level
def print_tree(self):
spaces = ' ' * self.get_level() * 3
prefix = spaces + "|__" if self.parent else ""
print(prefix + self.data)
if self.children:
for child in self.children:
child.print_tree()
def add_child(self, child):
child.parent = self
self.children.append(child)
def build_product_tree():
root = TreeNode("Electronics")
laptop = TreeNode("Laptop")
laptop.add_child(TreeNode("Mac"))
laptop.add_child(TreeNode("Surface"))
laptop.add_child(TreeNode("Thinkpad"))
cellphone = TreeNode("Cell Phone")
cellphone.add_child(TreeNode("iPhone"))
cellphone.add_child(TreeNode("Google Pixel"))
cellphone.add_child(TreeNode("Vivo"))
tv = TreeNode("TV")
tv.add_child(TreeNode("Samsung"))
tv.add_child(TreeNode("LG"))
root.add_child(laptop)
root.add_child(cellphone)
root.add_child(tv)
root.print_tree()
if __name__ == '__main__':
build_product_tree()
我知道 self.parent 的含义,但请有人解释一下:p = p.parent 和 child.parent = self
【问题讨论】:
-
在某些时候
p.parent将导致None将停止循环,然后您将计算循环运行的次数。 -
通过
p = p.parent,我们提升了一代人。因此,当当前节点有父节点时,将父节点设置为当前节点并增加级别。child.parent = self表示将child节点的父节点设置为当前节点(self)
标签: python python-3.x oop