#3830. [GESP202509 六级 C++] 第 12 题

[GESP202509 六级 C++] 第 12 题

nn 是树的节点数目,下列代码实现了树的广度优先遍历,其时间复杂度是( )。

void bfs(TreeNode* root) {
    if (!root) return;
    queue<TreeNode*> q;
    q.push(root);
    while (!q.empty()) {
        TreeNode* node = q.front();
        q.pop();
        cout << node->val << " ";
        if (node->left) q.push(node->left);
        if (node->right) q.push(node->right);
    }
}

{{ select(1) }}

  • O(n)O(n)
  • O(logn)O(\log n)
  • O(n2)O(n^2)
  • O(2n)O(2^n)