查 23 比了几次
还是那棵树(17、24、15、13、23 依次插入)。运行下面这段程序,它数的是"比了几次":
class BNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def insert(root, val):
if root is None:
return BNode(val)
if val < root.val:
root.left = insert(root.left, val)
elif val > root.val:
root.right = insert(root.right, val)
return root
def build():
root = None
for v in [17, 24, 15, 13, 23]:
root = insert(root, v)
return root
cur = build()
n = 0
while cur is not None:
n += 1
if 23 == cur.val:
break
cur = cur.left if 23 < cur.val else cur.right
print(n)
全部评论