非二叉树遍历方法

问题描述

我正在尝试创建一个python非二叉树类,其方法将允许我获取特定的节点,并将其他方法应用于找到的节点。

我从这个非常好的示例中的代码开始:https://www.youtube.com/watch?v=4r_XR9fUPhQ

添加一个方法,该方法接受与要查找的节点相对应的字符串(“ /”分隔,跳过根),递归搜索树,理论上,使用“ 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))

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...