You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java递归打印指定高度金字塔触发栈溢出问题排查

问题原因

栈溢出的核心原因是递归逻辑出现了无限循环递归,永远无法触达终止条件:

  • 当迭代值it增长到和入参height相等时,你会调用printPyramidRow(it - 1, height)进入递减打印流程
  • 但当it = height - 1重新进入方法时,判断it < height为真,又会反过来调用printPyramidRow(it + 1, height)回到it = height的状态
  • 两个分支反复横跳,根本走不到it <= 0的终止判断,栈帧持续堆积最终抛出溢出错误。
修复方法

给递归方法增加一个阶段标记,区分当前是递增打印阶段还是递减打印阶段,避免阶段跳转混乱,修正后可直接运行的代码如下:

public static void printPyramid(int height){
    if(height == 0) {
        return;
    }        
    printPyramidRow(1, height, false);
}

public static void printPyramidRow(int it, int height, boolean isDescending) {
    if(it <= 0) {
        return;
    }
    printRow(it);
    if (!isDescending) {
        if (it < height) {
            printPyramidRow(it + 1, height, false);
        } else {
            printPyramidRow(it - 1, height, true);
        }
    } else {
        printPyramidRow(it - 1, height, true);
    }
}

public static void printRow(int numOfStars) {
    for(int i = 0; i < numOfStars; i++) {
        System.out.print("*");
    }
    System.out.println();
}

调用printPyramid(5)即可输出预期的金字塔结构,不会再出现栈溢出问题。

内容的提问来源于stack exchange,提问作者user8672583

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.02 06:24:30