单选题 适中
#20440

以下代码实现了二叉树的深度优先搜索(DFS),并统计叶子结点的数量,则横线上应填写?( ) int countLeafNodes ( TreeNode * ro…

以下代码实现了二叉树的深度优先搜索(DFS),并统计叶子结点的数量,则横线上应填写?( )

int countLeafNodes(TreeNode* root) {
    if (root == nullptr) return 0;
    stack<TreeNode*> s;
    s.push(root);
    int count = 0;
    while (!s.empty()) {
        TreeNode* node = s.top();
        s.pop();
        if (node->left == nullptr && node->right == nullptr) {
            count++;
        }
        if (node->right) s.push(node->right);
        _____________________________________ // 在此处填入代码
    }
    return count;
}
未登录也能判分,登录后才会记录
答案与解析
正确答案:A
解析

空缺的位置在 while 循环的末尾,当前代码已经处理了右子树的压栈操作,需要补充左子树的处理逻辑。

程序使用栈(stack<TreeNode*>)来实现 DFS,空缺部分应该是一个类似的逻辑:如果 node 有左子节点,则将其压入栈。

本题答案为选项A。