【发布时间】: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