这棵树里有几个黑节点

👁️ 0 人浏览 💬 0 人评论 ❤️ 添加收藏

一棵小树: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 编译。)

提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论