【问题标题】:Recursion in java and maintaining states of variables across stacksjava中的递归和跨堆栈维护变量的状态
【发布时间】:2014-07-13 06:50:20
【问题描述】:

我试图解决 BST 中的一个问题,即“检查所有叶子是否处于同一水平”

在这个问题中,我需要不断增加每个堆栈调用的级别,但还要在所有调用中保持一个值,即最大级别。除此之外,我需要返回一个带有结果的布尔值。

解决起来很简单,我需要继续沿着树做,我这样做了

int maxlevel = 0;
public boolean allAtSameLevel(Node root, int level){
    if(root== null){
        return false;
    }
    if(root.left== null && root.right == null){
        if(maxlevel == 0){
            maxlevel = level;
        }
        return(level== maxlevel);
    }
    return allAtSameLevel(root.left, level+1) && allAtSameLevel(root.right, level+1) ;
}

我的问题是,对于需要共享的值,我必须在 java 中维护一个实例变量。有一个更好的方法吗?我的困惑是,因为它会先一直到右叶然后再上升,传递值将无济于事。有什么想法吗?

【问题讨论】:

    标签: java recursion tree pass-by-value


    【解决方案1】:

    诀窍是将子树的深度传达回堆栈的更高级别,但只有在左右深度相同时才这样做。你可以用一个简单的递归函数来做到这一点:

    int eqDepth(Node n) {
        if (n == null) return 0;     // This is a leaf, its subtree depth is zero
        int dLeft = eqDepth(n.left); // Make two recursive calls
        int dRight = eqDepth(n.right);
        // If one of the depths is negative, or the depths are different,
        // report it by returning negative 1:
        if (dLeft < 0 || dRight < 0 || dLeft != dRight) return -1;
        return 1+dLeft; // It's the same as dRight
    }
    

    有了这个功能,你可以在一行代码allAtSameLevel

    public boolean allAtSameLevel(Node root) {
        return eqDepth(root) >= 0;
    }
    

    这是一个demo on ideone.,它从一棵不平衡的树开始,得到一个-1

         a
       /   \
      b     c
     / \   / \
    d   e  f  -
    

    然后添加缺失的节点

         a
       /   \
      b     c
     / \   / \
    d   e  f  g
    

    并得到肯定的结果。

    【讨论】:

    • 感谢您的回答。但我认为这个解决方案是比较每个根的左右并返回值而不是整个树的叶节点。我对其进行了测试,只要根有两个孩子,它就会返回一个 >=0 的值。
    • @12rad 糟糕,我忘记在之前调用的结果中添加一个。它现在可以工作了 - 看看演示。
    • 是的,这行得通。因此,您无需向下计算级别,而是采用自下而上的方法来返回值并将其相加,然后进行比较。我觉得我需要多练习!不过谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-02
    • 2014-12-09
    • 2021-05-17
    • 2017-09-27
    • 2016-12-30
    • 2020-07-13
    • 2010-12-31
    相关资源
    最近更新 更多