【发布时间】:2021-01-12 03:53:31
【问题描述】:
我正在尝试创建一个 python 非二叉树类,其方法允许我获取特定节点,并将其他方法应用于找到的节点。
我从这个非常好的示例中的代码开始:https://www.youtube.com/watch?v=4r_XR9fUPhQ
我添加了一个方法,该方法接受与我正在寻找的节点对应的字符串(“/”分隔,跳过根),递归搜索树,理论上,使用“self”返回节点,所以我可以应用其他方法。
但是,当我 return(self) 时,它会返回一个非类型而不是节点。
如果这是一种糟糕的结构方式,请提供有关如何解决此问题的建议,或者提出另一种方法的建议!
提前致谢。
注意:到目前为止,这仅设置为匹配叶子,但如果我可以让该死的东西返回我想要的节点,我可以解决这个问题。
代码如下:
class TreeNode:
def __init__(self, data):
self.data = data
self.children = []
self.parent = None
self.forecast = 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 get_node(self, path):
segs = path.split('/')
sep = "/"
print(self.return_child_names())
if self.children:
for child in self.return_child_names():
if segs[0] == child:
found_child = segs.pop(0)
break
self.children[self.return_child_names().index(found_child)].get_node(sep.join(segs))
else:
print("Found the node!")
print(self)
print(self.data)
return(self)
def return_child_names(self):
return([c.data for c in self.children])
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()
return(root)
product_tree = build_product_tree()
product_tree.get_node("Laptop/Mac").print_tree()
【问题讨论】:
-
if self.children块中没有return。您应该返回递归调用的结果。 -
有趣,感谢您的反馈!当我在递归调用之后添加返回语句时,我确实得到了一个结果,但结果是树的顶部节点,而不是我找到的与我的路径匹配的节点......这是因为它正在返回“get_node”的第一次调用?
-
确保不是
return self,而是return self.children[...... -
知道了!非常感谢!
标签: python oop recursion tree python-class