ClawOJ 在线刷题在线判题 · 参考答案 · 完全免费

题库 / 3061310. 给定一棵二叉树,采用广度优先搜索 (BFS) 算法,…(2026-03)

3061310. 给定一棵二叉树,采用广度优先搜索 (BFS) 算法,…(2026-03)

难度 普及/提高- 时间限制 1000 ms 内存限制 256 MB 指针数组

题目描述

给定一棵二叉树,采用广度优先搜索 (BFS) 算法,返回右视图所有节点的值。其中右视图定义为:二叉树的右视图是从树的右侧看过去时可见的节点集合,即右视图中的每个节点都是某一层中最右侧的节点。

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x): val(x), left(nullptr), right(nullptr) {}
};

vector<int> rightSideView(TreeNode* root) {
    unordered_map<int, int> rightmostValueAtDepth;
    int max_depth = -1;

    queue<TreeNode*> nodeQueue;
    queue<int> depthQueue;
    nodeQueue.push(root);
    depthQueue.push(0);

    while (!nodeQueue.empty()) {
        TreeNode* node = nodeQueue.front(); nodeQueue.pop();
        int depth = depthQueue.front(); depthQueue.pop();

        if (node != NULL) {
            max_depth = max(max_depth, depth);

            rightmostValueAtDepth[depth] = node->val;

            nodeQueue.push(node->left);
            nodeQueue.push(node->right);

            depthQueue.push(________);
            depthQueue.push(________);
        }
    }

    vector<int> rightView;
    for (int depth = 0; ________; ++depth) {
        rightView.push_back(rightmostValueAtDepth[depth]);
    }
    return rightView;
};

作答说明

单选题:在选项里选出唯一正确的一项,提交后立即判定。答对得满分,答错可以重新提交(两次提交之间需要间隔 20 秒)。

题目来源

CCF GESP 2026 年 3 月认证 C++ 6 级试题,第 12 题。

去做这道题 → 浏览全部 5487 道题