这棵树一共几个节点
把 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;
};
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 count_nodes(BNode* node) {
if (node == nullptr) return 0;
return 1 + count_nodes(node->left) + count_nodes(node->right);
}
int main() {
cout << count_nodes(build()) << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)
全部评论