【发布时间】:2011-04-25 04:09:53
【问题描述】:
我在这里阅读了其他几篇看起来相似的文章,但并没有完全回答我的问题。我收到了一个问题,要求为二叉树中的每个节点分配其各自的深度。我就是不明白。
这是我的代码供参考:
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);
}
}
【问题讨论】:
-
感谢所有回复我帖子的人。我明白我现在想的都是错的。我会离开并尝试根据您告诉我的内容修复代码并发布我的最终结果。我不想在没有完全理解的情况下使用某人的代码(尽管我很感激你为我发布了它,谢谢)。
-
有效!我做了一个递归算法,最终匹配了库珀先生的算法。它实际上是更大算法的一部分,该算法将 x 和 y 坐标分配给树节点。该算法现在在原始问题中。
标签: c++ recursion binary-tree