为每个节点分配深度

时间:2010-10-14 01:39:16

标签: c++ recursion binary-tree

我在这里看了几篇看似相似的文章,但没有完全回答我的问题。我已经给出了一个分配的问题,即为二叉树中的每个节点分配各自的深度。我只是不太明白。

供参考,这是我的代码:

struct treeNode {
   int item;
   int depth;
   treeNode *left;
   treeNode *right;
};
typedef treeNode *Tree;

int assignDepth(Tree &T, int depth)
{
    if(T!=NULL)
    {
        depth = assignDepth(T->left, depth++);
        T->depth = depth;
        depth = assignDepth(T->right, depth++);
    }
    else //leaf
        return depth--;
}

我尝试用笔和纸来完成它看起来很好,但我的桌面检查技能显然不足。

有人能指出我正确的方向吗?这是我第一次使用树木,递归不是我的强项。

答案:

void treecoords(Tree &T, int depth)
{
    static int count = -1; //set to -1 so the precrement before assignment doesn't give the wrong values
    if(T!=NULL)
    {
        treecoords(T->left, depth+1); //depth decrements automatically once this function call is removed from the stack
        count++;
        T->x = count;
          T->y = depth;
        treecoords(T->right, depth+1);
    } 
}

6 个答案:

答案 0 :(得分:3)

你不需要

else //leaf
    return depth--;

您也不想增加深度变量,只需将深度+ 1传递给下一次交互。

此外,无需返回值。

试试这个:

void assignDepth(Tree T, int depth)
{
    if(T!=NULL)
    {
        assignDepth(T->left, depth+1);
        T->depth = depth;
        assignDepth(T->right, depth+1);
    }
}

答案 1 :(得分:2)

嗯,对于初学者来说,你正在使用后递增/递减,你可能意味着++depth/--depth用于正确的赋值和else返回;

另外,为什么要将指针作为参考变量传递?

答案 2 :(得分:1)

int assignDepth(Tree &T, int depth)

您已将Tree定义为指向treeNode的指针。您无需通过引用传递它。您可以修改指向的节点。

{
    if(T!=NULL)
    {
        depth = assignDepth(T->left, depth++);

后缀++可确保您将原始depth传递下来。那不是你想要的。在此之前递增depth,忘记将其作为函数结果返回。

    T->depth = depth;

没关系。

        depth = assignDepth(T->right, depth++);

与之前的递归调用类似,但在此处不应修改depth,因为它已经递增。

    }
  else //leaf
        return depth--;

您不需要返回任何深度信息(或者是未说明的要求吗?)。

}

干杯&第h。,

答案 3 :(得分:1)

  1. 到达叶子节点后​​,您不再关心它的深度,因此返回值似乎无效。

  2. 在两个陈述中:

    depth = assignDepth(T->left, depth++);
    // and
    depth = assignDepth(T->right, depth++);
    
  3. 你有两次修改depth而没有插入序列点的未定义行为(虽然看起来应该有,但是在左右两边之间的序列点分配)。

答案 4 :(得分:1)

  1. 当节点为NULL时,为什么还要返回。根据您的规范,您不需要返回任何深度
  2. 在其他情况下,您只需增加深度并发送到函数调用。以下是我的代码版本

    void assignDepth(Tree& T,int depth) {     if(T == NULL)         返回;     其他     {         T->深度=深度;         if(T-> left!= NULL)assignDepth(T-> left,depth + 1);         if(T-> right!= NULL)assignDepth(T-> right,depth + 1);     } }

答案 5 :(得分:1)

我有一个稍微复杂的设计,有不同的节点类型并做了这个,所以我认为id共享。

如果你的树在节点类型(二进制,一元等)上有所不同,那么值得简化传统方法以避免讨厌的嵌入式IF检查节点类型。

两个功能:

  • 1:从根目录开始,遍历每个节点并检查其距离 root通过递归调用自身并为每个父级添加1。给 每个节点都有一个深度变量来存储它。
  • 2:从树中的完整节点集运行MAX检查 针对每个节点深度,最高数量将等于深度 这棵树。

以这种方式处理会删除显式类型检查,并且无论是否有一个,两个或一百个子节点,都只需对节点进行计数。

希望这有助于某人!