【问题标题】:Finding the number of nodes at a given depth in a tree查找树中给定深度的节点数
【发布时间】:2020-10-09 12:54:47
【问题描述】:

我有点难以理解为什么我的递归方法无法解决问题。它是一种用于在二叉搜索树中生成给定深度的节点数的方法。我已经获得了测试用例,但我遇到了一个问题,对于树上的测试用例,我得到了一个深度的正确答案,但同一棵树上另一个深度的错误答案。我很困惑为什么我得到两个不同的答案,即使答案不正确。下面附上我的代码和测试代码。

树形结构

        D
       / \
      B   F (get correct output for this depth) (depth 1, number of Nodes 2)
     / \ / \
    A  C E  G (incorrect answer at this depth) (depth 2, number of Nodes 4 but getting 1)

节点定义代码:

public class simpleBST<Key extends Comparable<Key>, Value> {
private Node root;             // root of BST

static boolean verbose = true;   // set to false to suppress positive test results
private class Node {
    private Key key;           // key
    private Value val;         // associated data
    private Node left, right;  // left and right subtrees

    public Node(Key key, Value val) {
        this.key = key;
        this.val = val;
    }

我的代码

public int numNodesAtDepth(int d) {
return numNodesAtDepthHelper(root,d,0);
}
public int numNodesAtDepthHelper(Node temp,int d,int cdepth)
{
    if(temp==null)
    {
        return 0;
    }
    if(cdepth==d)
    {
        return 1;
    }
    return numNodesAtDepthHelper(temp.left,d,cdepth++) + numNodesAtDepthHelper(temp.right,d,cdepth++);
}

测试代码

testnumNodesAtDepth("DBACFEG",1, 2);

结果

testnumNodesAtDepthD:正确键:[ DBACFEG] 实际:2

测试代码

testnumNodesAtDepth("DBACFEG",2, 4);

结果

testnumNodesAtDepthD:错误键:[DBACFEG]预期:4实际:1

测试代码只是用给定的键创建一棵树并调用方法。使用格式 testnumNodesAtDepth("Keys"(nodes) 要传入, depth, number of "keys"(nodes) 在那个深度); 我感到困惑的是我的代码如何在同一棵树上得到两个不同的答案,以及如何修复这个错误。

【问题讨论】:

  • 树是在函数testnumNodesAtDepth处创建的,你在这里调用numNodesAtDepth。能否在题中也加入 testnumNodesAtDepth 函数?

标签: java


【解决方案1】:

问题就在这里:

return numNodesAtDepthHelper(temp.left,d,cdepth++) + numNodesAtDepthHelper(temp.right,d,cdepth++);

当您调用cdepth++ 时,它会增加cdepth 的值并返回旧值。因此,如果 cdepth 为 1,则上述行等价于:

return numNodesAtDepthHelper(temp.left,d,1) + numNodesAtDepthHelper(temp.right,d,2);

解决方案是使用cdepth + 1 而不是cdepth++

【讨论】:

  • 这是正确的,我不知道它保留了旧值,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-27
  • 2022-01-27
  • 1970-01-01
  • 2014-01-21
  • 2015-05-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多