查 23 比了几次

👁️ 0 人浏览 💬 0 人评论 ❤️ 添加收藏

还是那棵树(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)
提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论