【问题标题】:Setting the root node of tree to None将树的根节点设置为无
【发布时间】:2016-03-15 19:42:53
【问题描述】:

当删除单节点树中的根(恰好是叶子本身)时,我需要将根节点更改为无。我不想得到一个 self.value = self.left = self.right = None 的空节点。

我尝试设置 self = None ,如下面的代码所示,但由于某种原因它不起作用,删除 (del self) 也不起作用。删除叶子很容易,因为您只需要设置 previous.right = None 或 previous.left = None 就可以了。但是显然没有参考根来帮助解决这种情况。

是否甚至可以从二进制节点更改根的类型并将其设为 None 甚至是整数等?因为正如您在代码中看到的,设置 self 不起作用

class BinaryNode:
    def __init__(self, value, left = None, right = None):
        '''
        Initiate a Binary-tree
        :param value: float | int | str
        :return: None
        '''
        self.value = value
        self.left = left
        self.right = right

    def delete_root(self):
        '''
        Delete the root of the tree
        :return: None
        '''
        if not(self.right or self.left): #Base case: the root is childless
            self = None              #Doesnt work!!! 
        else:
            self.left.get_max() #get_max is a method that replaces the root with a leaf

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    你无法做到这一点。对根节点的引用保存在其他地方(例如各种用户函数中的局部变量),并且类本身无法更改这些引用。

    您可能想要做的是在用户代码和根节点之间添加一个额外的间接层。通常这是某种Tree 类,除了(可能是None)根节点引用之外,它还可以跟踪其他有用的东西,例如树中有多少值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多