【发布时间】:2017-04-01 08:46:40
【问题描述】:
我正在尝试破译几年前发布的这段代码:How to implement a binary search tree in Python?
我感到困惑的部分是这个部分:
class Node:
def __init__(self, val):
self.l_child = None
self.r_child = None
self.data = val
def binary_insert(root, node):
if root is None:
root = node
else:
if root.data > node.data:
if root.l_child is None:
root.l_child = node
else:
binary_insert(root.l_child, node)
else:
if root.r_child is None:
root.r_child = node
else:
binary_insert(root.r_child, node)
然后通过执行以下操作调用类和函数:
r = Node(3)
binary_insert(r, Node(7))
binary_insert(r, Node(1))
binary_insert(r, Node(5))
我的问题是:self.data 在传递到 binary_insert 函数时发生了什么? node.data 和 root.data 是从哪里来的?
【问题讨论】:
-
self是Node类的实例。root和node也是Node类的实例。想一想...... self=root; self.data