查 23 比了几次

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

还是那棵树。运行下面这段程序,它数的是「比了几次」:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

struct BNode {
    int val;
    BNode* left = nullptr;
    BNode* right = nullptr;
};

BNode* insert(BNode* root, int val) {
    if (root == nullptr) return new BNode{val};
    if (val < root->val) root->left = insert(root->left, val);
    else if (val > root->val) root->right = insert(root->right, val);
    return root;
}

BNode* build() {
    BNode* root = nullptr;
    for (int v : {17, 24, 15, 13, 23}) root = insert(root, v);
    return root;
}

int main() {
    BNode* cur = build();
    int n = 0;
    while (cur != nullptr) {
        n++;
        if (23 == cur->val) break;
        cur = 23 < cur->val ? cur->left : cur->right;
    }
    cout << n << endl;
}

(本题用 g++ -std=c++17 -O0 编译。)

提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论