删一个叶子后还剩几个
把 17、24、15、13、23 依次插进一棵空的 BST。运行下面这段程序:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct BNode {
int val;
BNode* left = nullptr;
BNode* right = nullptr;
};
int alive = 0; // 还有几个节点没有 delete
BNode* make(int v) {
alive++;
return new BNode{v};
}
void drop(BNode* nd) {
alive--;
delete nd;
}
BNode* insert(BNode* root, int val) {
if (root == nullptr) return make(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* root = build();
BNode* leaf = root->left->left; // 13
root->left->left = nullptr;
drop(leaf);
cout << alive << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)
全部评论