二叉树中所有节点的深度总和(路径长度)

时间:2012-11-16 21:06:38

标签: binary-tree depth

我正在尝试实现一个函数来计算二叉树的路径长度,但我无法得到正确的答案。你能看看我做错了什么吗?以下是我的代码:

public int pathLength() {
    int sum = 0;
    int c = 1;
    pathLength(root, sum);
    return sum;
}

public int pathLength(Node n, int sum) {
    if(n.isRoot())
        sum+= 0;
    if(n.left == null && n.right == null)
        return;
    c++;
    if(n.left != null)
        sum += c;
    if (n.right != null)
        sum+=c;
    pathLength(n.left, sum);
    pathLength(n.right, sum); 

}

2 个答案:

答案 0 :(得分:1)

这段代码有很多问题。它甚至不会编译因为a)在第二个函数中c从未声明(它在第一个中是局部的)而b)第二个函数永远不会返回一个值。

但最大的问题是你宣布第二个功能的方式。 “sum”按值传递。这基本上意味着每次调用函数时都会创建一个“sum”的新副本,并在函数结束时被丢弃。

您想要做的是通过引用传递。执行此操作时,实际的sum变量(而不是副本)将传递给函数。所以你的代码可能如下所示:

public void pathLength(Node n, int& sum) {
    //if(n.isRoot())     <- not sure what this is for
    //    sum+= 0;

    sum += 1;   // Increment for this node

    //if(n.left == null && n.right == null)
    //    return;      // This conditional is not needed with next 2 if statements

    //c++;    <- Don't know what c is for

    // Recursively call for child nodes
    if(n.left != null)
        pathLength(n.left, sum);
    if (n.right != null)
        pathLength(n.right, sum); 
}

请注意,这会计算树中的所有节点。我认为这就是你想要的。如果你想找到最深的节点,那就不同了。

答案 1 :(得分:0)

是否因为您将c的初始值设置为1而不是0? 根的子女应该在2级,深度为1.

相关问题