第23816题 单选题
给定C++实现的二叉树广度优先搜索算法,判断指定二叉树搜索时的可能输出是以下哪一项?
#include <iostream>
#include <queue>
using namespace std;

// 二叉树节点的定义
struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

// 宽度优先搜索(BFS)迭代实现
TreeNode* bfs(TreeNode* root, int a) {
    if (root == nullptr) return nullptr;
    queue<TreeNode*> q;
    q.push(root);
    while (!q.empty()) {
        TreeNode* node = q.front();
        q.pop();
        if (node->val == a)
            return node;

        cout << node->val << " "; // 先访问当前节点
        if (node->left) q.push(node->left); // 将左子节点入队
        if (node->right) q.push(node->right); // 将右子节点入队
    }
    return nullptr;
}

使用以上算法,在以下二叉树中搜索数值时,可能的输出是( )。

二叉树结构

A

5 2 -4 3 17 9

B

-4 2 3 5 9 17

C

5 2 17 -4 3 9

D

以上都不对

程序运行统计
暂无判题统计