python - 非二叉树遍历方法
问题描述
我正在尝试使用允许我获取特定节点并将其他方法应用于找到的节点的方法创建一个 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()
解决方案
问题出在函数中get_node
:您并不总是返回一个值。值得注意的是,在以下块中没有return
,因此该函数可以返回None
:
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))
您从递归调用中获得的值get_node
被忽略。您实际上应该返回它:
return self.children[self.return_child_names().index(found_child)].get_node(sep.join(segs))
推荐阅读
- php - 图像在 fpdf 中超出表格
- android - 如何通过直接令牌规范方法在 Google Pay 集成中获取公钥
- sql - 根据前一列序列更新列
- google-cloud-firestore - 在 Firebase Firestore 模拟器中设置身份验证信息
- android - “Firebase 存储异常:对象不存在”我不知道为什么
- flutter - 从子组件访问值和函数
- angular - Angular 8 href 重定向
- php - 获取组织名称并将其缩写,其变体中省略了“of”和“and”,但也包含在其他变体中
- javascript - moduleDirectories 键无法导入我的测试工具
- python - 当你重塑它时,numpy 数组的 getrefcount 发生了什么