查 23 比了几次
还是那棵树。运行下面这段程序,它数的是「比了几次」:
#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 编译。)
全部评论