c++ - 为每个节点分配深度

标签 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);
    } 
}

最佳答案

你不需要

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);
    }
}

关于c++ - 为每个节点分配深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3929448/

相关文章:

c++ - 正则表达式 (C++) 只接受一个字符,没有更多

c++ - 如何在C++中将float转换为unsigned int?

javascript - 如何折叠多维数组

java - Java 中的斐波那契内存/动态编程

c++ - OpenCV、C++、使用 HoughLinesP 进行线检测

c++ - flush 属性在 SimpleFileChannel 中的工作原理

c++ - 用于打印斐波那契树元素的递归 C++ 函数

c++ - 二叉搜索树无法正常工作? (解析错误)

c++ - 如何不重复打印树的代码

algorithm - 给定高度的二叉搜索树的数量