插入 20 后它挂在谁下面
还是那棵树,再插一个 20。运行下面这段程序:
#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();
while (true) {
BNode* nxt = 20 < cur->val ? cur->left : cur->right;
if (nxt == nullptr) break;
cur = nxt;
}
cout << cur->val << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)
全部评论