我在Java中写了一种递归方法来计算树的高度,我的问题是如何获得这种方法以一次打印高度

发布于 2025-01-25 13:31:06 字数 386 浏览 3 评论 0原文

因此,这是我的方法:

public int getHeight(IntTreeNode root) {
        if(root == null) {
            return 0;
        }
        int height = 1 + Math.max(getHeight(root.left), getHeight(root.right));
         
        System.out.println(height);
        }
        return height;
    }

我知道,由于这是一种递归方法,它将打印循环的高度,直到达到最终高度,但是我想要的是这种方法仅打印最终高度。关于如何使这项工作的任何想法?谢谢。

So here is my method:

public int getHeight(IntTreeNode root) {
        if(root == null) {
            return 0;
        }
        int height = 1 + Math.max(getHeight(root.left), getHeight(root.right));
         
        System.out.println(height);
        }
        return height;
    }

I know that since it's a recursive method it will print the height in loops until it reaches the final height, but what I want is for this method to print the final height only. Any ideas on how to make this work anyone? thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淤浪 2025-02-01 13:31:06

您应该使用第二种方法(例如printheight)打印高度,并使用getheight方法仅返回高度。

E. G。:

public int getHeight(IntTreeNode root) {
    if(root == null) {
        return 0;
    }
    int height = 1 + Math.max(getHeight(root.left), getHeight(root.right));
    return height;
}
public void printHeight() {
    System.out.println(getHeight());
}

You should use a second method e. g. printHeight to print the height and use the getHeight method only to return the height.

E. g.:

public int getHeight(IntTreeNode root) {
    if(root == null) {
        return 0;
    }
    int height = 1 + Math.max(getHeight(root.left), getHeight(root.right));
    return height;
}
public void printHeight() {
    System.out.println(getHeight());
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文