我在这里阅读了一些其他文章,看起来很相似,但没有完全回答我的问题。我已经给出了一个分配的问题,即为二叉树中的每个节点分配相应的深度。我无法完全理解。为每个节点分配一个深度
供参考,这是我的代码:
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);
}
}
谢谢大家谁回复我的帖子。我明白我现在正在考虑这一切都是错误的。我会走开,并尝试修复代码,给你告诉我并发布我的最终结果。我不想在没有完全理解的情况下使用某些代码(尽管我很欣赏你已经发布了它,谢谢)。 – xyzjace 2010-10-14 02:02:52
它的工作原理!我做了一个递归算法,最终匹配库珀先生的。它实际上是一个更大的算法的一部分,它将x和y坐标分配给树节点。该算法现在在原始问题中。 – xyzjace 2010-10-14 02:24:57