我有这样的元组。
t = (5, (3, (20, none, none), (21, none, none)), (10, (1, none, none), none))
我想从中构建一棵树。树类看起来像这样。
class TreeNode(object):
def __init__(self,x=None,l=None,r=None):
self.x = x
self.l = l # left node
self.r = r # right node
我正在递归地构建树。我检查当前节点是否为None
,然后将当前节点设置为新的TreeNode
类。但这并不像预期的那样有效。
def build(current_node, tupl):
if tupl:
if current_node is None:
current_node = TreeNode() # I think this removes link to the trees node.
current_node.x = tupl[0]
build(current_node.l, tupl[1])
build(current_node.r,tupl[2])
这是我如何调用构建函数
root = TreeNode() # TreeNode is tree class
build(root,t)
# I try to print the tree level by level but tree only has root node
但是这个构建函数运行正常。
def build(curr,t):
if t:
curr.x = t[0]
try:
if t[1] is not None:
curr.l = TreeNode()
build(curr.l,t[1])
except Exception:
pass
try:
if t[2] is not None:
curr.r = TreeNode()
build(curr.r,t[2])
except Exception:
pass
我试图理解为什么第一个构建函数失败。
答案 0 :(得分:2)
在Python中,您无法在函数中重新分配变量,并且这些值对于调用上下文是可见的。通过调用current_node = TreeNode(),current_node被分配给外部不可见的新对象。
def build(current_node, tupl):
if tupl:
if current_node is None:
current_node = TreeNode()
current_node.x = tupl[0]
build(current_node.l, tupl[1])
build(current_node.r,tupl[2])
在第二个示例中,您传入的是TreeNode实例,然后操纵它的属性而不是重新分配它。因此,当前上下文中的curr.l / curr.r和下一次调用中的curr仍然引用同一个对象。
def build(curr,t):
if t:
curr.x = t[0]
....
if t[2] is None:
curr.r = TreeNode()
....
# reference link is not broken
build(curr.r, t[2])