用下面 BFS 代码遍历给定二叉树(1 的孩子 2、3;2 的孩子 8、9;3 的右孩子 6;9 的孩子 4、5;6 的右孩子 7;7 的孩子 10、11),可能的输出是:
void bfs(TreeNode* root) {
if (!root) return;
queue<TreeNode*> q; q.push(root);
while (!q.empty()) {
TreeNode* cur = q.front(); q.pop();
cout << cur->val << " ";
if (cur->left) q.push(cur->left);
if (cur->right) q.push(cur->right);
}
}
- A. 1 2 8 9 4 5 3 6 7 10 11
- B. 1 2 3 4 5 6 7 8 9 10 11
- C. 1 2 3 8 9 6 4 5 7 10 11
- D. 1 2 3 8 9 4 5 6 7 10 11
正确答案:C