这棵树一共几个节点

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

运行下面这段程序:

#include <iostream>
#include <queue>
#include <string>
#include <vector>
using namespace std;

struct TNode {
    string name;
    TNode* left = nullptr;
    TNode* right = nullptr;
};

TNode* build() {
    TNode* root = new TNode{"总部"};
    root->left = new TNode{"华北"};
    root->right = new TNode{"华南"};
    root->left->left = new TNode{"北京"};
    root->left->right = new TNode{"天津"};
    root->right->right = new TNode{"广州"};
    return root;
}

int count_nodes(TNode* 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 编译。)

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

                        
👩‍🏫
AI
💬 题目评论

全部评论