简体   繁体   English

在树遍历递归算法(Java)中评估堆栈溢出错误是否可行

[英]Evaluating if a stack overflow error is possible in a tree traversal recursive algorithm (Java)

What is the best way to determine theoretically (ie, without actually executing it) the circumstances in which a certain tree traversal recursive algorithm will produce a stack overflow in Java? 在理论上确定(即,没有实际执行它)某种树遍历递归算法会在Java中产生堆栈溢出的情况下,最好的方法是什么?

In order to clarify my question, consider the following example. 为了澄清我的问题,请考虑以下示例。 Given a simple binary tree implemented in Java: 给定一个用Java实现的简单二叉树:

public class Node {
    private int value;
    private Node left;
    private Node right;
    ...

    //in-order traversal
    public void inOrder() {
        if (left != null) {
            left.inOrder();
        }
        System.out.println(value);
        if (right != null) {
            right.inOrder();
        }
    }
}

In this algorithm, the maximum number of nested recursive calls is linear with respect to the depth of the tree. 在该算法中,嵌套递归调用的最大数量相对于树的深度是线性的。 So how can I estimate which is the maximum depth of the tree that will allow an in-order traversal algorithm (or similar) to complete without throwing a stack overflow error? 那么如何估计哪一个树的最大深度允许有序遍历算法(或类似)完成而不会引发堆栈溢出错误?

If the maximum stack size is assigned by thread by means of the -Xss option , is it correct to just divide this number to an estimation of each stack frame used by my recursive algorithm? 如果最大堆栈大小是由线程通过-Xss选项分配的,那么将此数字除以我的递归算法使用的每个堆栈帧的估计是否正确?

And is it correct to estimate the size of each stack frame by adding the size of parameters and local variables to the size of the program counter, where the program counter size depends on the architecture (32 bits vs 64 bits, etc...). 通过将参数和局部变量的大小添加到程序计数器的大小来估计每个堆栈帧的大小是正确的,其中程序计数器大小取决于体系结构(32位对64位等等) 。

Am I missing something else? 我错过了别的什么吗?

UPDATE: 更新:

I do know that a recursive algorithm can be converted to an iterative one in order to avoid stack overflow errors. 我知道递归算法可以转换为迭代算法,以避免堆栈溢出错误。 This is just a theoretical question regarding recursive algorithms. 这只是关于递归算法的理论问题。

I understand that this is mostly theoretical question but it is valid question. 我知道这主要是理论问题,但这是有效的问题。 You are right in your estimates. 你的估计是正确的。 Except stack goes to Xms but local variables go to Xmx. 除了堆栈到Xms,但局部变量转到Xmx。 So, based on real data what you use on each iteration and real size of available RAM depth of tree really varies. 因此,基于实际数据,您在每次迭代时使用的内容以及树的可用RAM深度的实际大小确实会有所不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM