【问题标题】:Java Recursion Count ParameterJava 递归计数参数
【发布时间】:2015-02-20 03:37:47
【问题描述】:

我正在编写一个递归调用来查看两个节点 (n & m) 是否包含在二叉树的子树中。这是函数:

public static boolean containsNodes(int n, int m, TreeNode node, int count){
    if(node == null) return false;
    if( count == 2) return true;
    if(node.getData() == m || node.getData() == n){
        count++;
    }
    return containsNodes(n, m, node.getLeft(), count) || 
           containsNodes(n, m, node.getRight(), count);

}

看起来计数在以后的调用中永远不会更新,即使条件node.getData() == m || node.getData() == n 为真'。为什么会这样?

【问题讨论】:

  • 考虑一个简单的 3 节点树(有 2 个子节点的父节点)。父节点有一个左节点和一个右节点。即使左右的数据分别为“n”和“m”,此方法也会失败,因为计数在每个分支上都是独立的。您最好传递包含计数的对象而不是用于确定计数的原语,因为按值传递会导致这里出现问题。也许我误解了你希望它如何工作。

标签: java algorithm recursion tree depth-first-search


【解决方案1】:

即使您找到nm 两次,此代码也会返回true。返回一个“掩码”代替boolean,并在找到m 时设置位0,在找到n 时设置位1。添加一个包装器,它为 3 的“掩码”返回 true,为其他所有内容返回 false

public static boolean containsNodes(int n, int m, TreeNode node) {
    return containsNodesMask(n, m, node, 0) == 3;
}
private static int containsNodesMask(int n, int m, TreeNode node, int mask) {
    if (node == null) return mask;
    if (node.getData() == m) mask |= 2;
    if (node.getData() == n) mask |= 1;
    if (mask == 3) return mask; // Short-circuit
    mask = containsNodes(n, m, node.getLeft(), mask);
    if (mask == 3) return mask; // Short-circuit again
    return containsNodes(n, m, node.getRight(), mask);
}

【讨论】:

  • 这个解决方案不起作用;如上所述,考虑一棵树 s.t. nm 是单个父节点p 的左右(分别)子节点。
猜你喜欢
  • 1970-01-01
  • 2018-06-12
  • 1970-01-01
  • 2017-09-07
  • 2014-12-28
  • 1970-01-01
  • 2016-03-10
  • 2016-07-22
  • 2015-10-10
相关资源
最近更新 更多