请将下列树的深度优先遍历代码补充完整,横线处应填入( )。
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x): val(x), left(nullptr), right(nullptr) {}
};
void dfs(TreeNode* root) {
if (!root) return;
______<TreeNode*> temp; // 在此处填写代码
temp.push(root);
while (!temp.empty()) {
TreeNode* node = temp.top();
temp.pop();
cout << node->val << " ";
if (node->right) temp.push(node->right);
if (node->left) temp.push(node->left);
}
}根据上下文和C++语法规则确定空缺处应填的内容,关注函数调用参数、表达式和返回值类型。
填空时注意语法完整性:分号、括号匹配、函数参数类型和个数、返回值类型。
【考点】stack|DFS 迭代实现|容器 top() 方法
GESP 六级《C++标准库容器》模块。命题人放这道题,就是卡住那些只背 vector/queue 语法的同学——stack 独有的 top() 方法,他们根本不会写。