这棵树里有几个黑节点
一棵小树:17 是黑的根,左边挂红色的 15,右边挂黑色的 24,15 的左边还挂着红色的 13。
运行下面这段程序:
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;
struct RNode {
int val;
string color;
RNode* left = nullptr;
RNode* right = nullptr;
};
RNode* rb_tree() {
RNode* root = new RNode{17, "黑"};
root->left = new RNode{15, "红"};
root->right = new RNode{24, "黑"};
root->left->left = new RNode{13, "红"};
return root;
}
int count_black(RNode* node) {
if (node == nullptr) return 0;
int n = node->color == "黑" ? 1 : 0;
return n + count_black(node->left) + count_black(node->right);
}
int main() {
cout << count_black(rb_tree()) << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)
全部评论