关于树数据结构的问题,打印每个级别的总和(级别总和=兄弟数据的总和)?

发布于 2024-10-04 06:35:22 字数 1084 浏览 1 评论 0原文

下面我写了一段代码来回答这个问题。请你告诉我 1) 如果您在我的代码中发现任何缺陷 2)任何其他最佳解决方案

问题: 关于树数据结构的问题,打印每个级别的总和(级别总和=兄弟数据的总和)?

struct tree{
             int data;
             struct *left;
             struct *right;
 };

API原型是void EachLevelSum(struct tree *root);

我的答案是

void EachLevelSum(struct tree *root )
{
     static int level=0;
     static int a[100] = {0}; // I am assuming , at MAX 100 levels in tree

     if( root == NULL )
     {
           return;
     }
     else
     {
           a[level += root->data;

           level++;
           EachLevelSum(root->left);
           level--;      

           level++;
           EachLevelSum(root->right);
           level--;      

           if( level == 0 )
           {
               int i;
               for( i=0; i<100 && a[i]!=0 ; i++)
               {
                   printf("\n level: %d sum = %d", i,  a[i] );
               }

           }
     }

}

Below I wrote a piece of code to answer this question. Colud you please tell me
1) if you find any defects in my code
2) any other best solution ?

Question:
Question on Tree data structure, print each level sum ( level sum = sum of siblings data ) ?

struct tree{
             int data;
             struct *left;
             struct *right;
 };

API protype is void EachLevelSum(struct tree *root);

My answer is

void EachLevelSum(struct tree *root )
{
     static int level=0;
     static int a[100] = {0}; // I am assuming , at MAX 100 levels in tree

     if( root == NULL )
     {
           return;
     }
     else
     {
           a[level += root->data;

           level++;
           EachLevelSum(root->left);
           level--;      

           level++;
           EachLevelSum(root->right);
           level--;      

           if( level == 0 )
           {
               int i;
               for( i=0; i<100 && a[i]!=0 ; i++)
               {
                   printf("\n level: %d sum = %d", i,  a[i] );
               }

           }
     }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

寂寞美少年 2024-10-11 06:35:22

我觉得这样就很好了!不过,我可以说一两件事,这可能会帮助你改进它。

1——静态变量的使用。这并不被禁止,但你应该避免这种情况。现在,您会如何看待您的解决方案本质上是递归的,并且您需要在调用之间共享数据?

一般方法是使用第二个函数,它包装递归调用,并向其传递额外的参数。在你的情况下:

void eachLevelSum(struct tree*);
static void eachLevelSumRecursive(struct tree*, int level, int* results);

然后,类似:

void eachLevelSum(struct tree* t) {
    int results[100];
    eachLevelSumRecursive(t, 0, results);

    return;
}

然后在你的递归函数中,每当你进入递归时,你可以将 level 参数作为 level + 1 传递,而不是像这样执行 level++ 和 level-- =D :

eachLevelSumRecursive(t->left, level + 1, results);
eachLevelSumRecursive(t->right, level + 1, results);

注意这不仅是干净一点,它还有其他优点。例如,这种方法可以在多线程环境中使用,而另一种则不能,因为它依赖于静态变量。

2 -- 您可能希望使用 typedef 和改变结构的函数进一步封装您的树。如果您想了解更多这方面的信息,请直接询问。不过,这对于您的锻炼来说根本不是必要的。

3 -- 记住函数名称通常以小写字母开头。

这就是我要说的一切,你的代码非常干净!恭喜!

I think that's pretty good! I can say a thing or two, however, that may help you improve it.

1 -- The use of static variables. It's not forbidden, but you should avoid this. Now, how would you, seeing as your solution is recursive in nature, and you need shared data between calls?

The general approach is to use a second function, that wraps the recursive call, and passes extra parameters to it. In your case:

void eachLevelSum(struct tree*);
static void eachLevelSumRecursive(struct tree*, int level, int* results);

And then, something like:

void eachLevelSum(struct tree* t) {
    int results[100];
    eachLevelSumRecursive(t, 0, results);

    return;
}

Then in your recursive function, whenever you go into recursion, you can pass the level parameter as level + 1 instead of doing level++ and level-- =D like this:

eachLevelSumRecursive(t->left, level + 1, results);
eachLevelSumRecursive(t->right, level + 1, results);

Note this is not only a bit cleaner, it has other advantages. For example, this approach can be used in a multithreaded environment, while the other one can't, since it relies on static variables.

2 -- You may want to further encapsulate your tree using typedefs, and functions that alter the structure. If you want more information on this, ask away. It's not at all necessary for your excercise, though.

3 -- Remember function names usually begin with lowercase letters.

And that's everything I have to say, your code is pretty clean! Congratulations!

开始看清了 2024-10-11 06:35:22

您的代码似乎做得正确。在英语中,您的逻辑是这样的 -

对于您下降到树中的每个级别(左侧和右侧),跟踪您的深度并将data添加到全局总和跟踪变量a.

除非你对你的结构做出重大改变 - 这是唯一的方法(我能想到的)

Your code seems to do it correctly. In English your logic states -

For every level that you descend into the tree (both left and right), keep track of your depth and add data to a global sum-tracking variable a.

Unless you make significant changes to your structure - that's the only way to do it (that I can think of)

-柠檬树下少年和吉他 2024-10-11 06:35:22

我会避免使用 level 作为全局变量。在这种特殊情况下,这并不重要,因为没有线程或类似的复杂情况。但养成避免使用全局变量的习惯是有好处的。

除非您必须使用全局变量并且需要小心,否则总是优先使用局部变量而不是全局变量。

我将在方法中添加 level 作为参数,而不是执行 level++ 和 level--,而是简单地将 level+1 传递给方法调用。

I would avoid using level as a global variable. In this particular case, it doesn't matter that much as there is no complication of threading or anything like that. But it's good to make it a habit to avoid using global variables.

It's always preferred to use a local variable than a global one unless you have to use a global variable and you need to be careful.

I would add level as a argument in the method, and instead of doing level++ and level--, I'll simply pass level+1 to the method call.

在风中等你 2024-10-11 06:35:22

我认为你的代码很好。

作为替代方案,您可以使用 BFS 搜索: http://en.wikipedia.org/wiki/Breadth -first_search。这是示例 C# 代码

    class Tree
    {
        public int data;
        public Tree Left;
        public Tree Right;


            static int[] levels = new int[100];

            static void EachLevelSum(Tree root)
            {
                // keeps track of each tree node's level
                Dictionary<Tree, int> treeLevels = new Dictionary<Tree,int>();
                treeLevels.Add(root, 0);

                // Do a BFS search and update the level of each node
                Queue<Tree> trees = new Queue<Tree>();
                trees.Enqueue(root);

                while (trees.Count != 0)
                {
                    Tree node = trees.Dequeue();
                    int level = treeLevels[node];
                    if (node.Left != null)
                    {
                        treeLevels.Add(node.Left, level + 1);
                        trees.Enqueue(node.Left);
                    }
                    if (node.Right != null)
                    {
                        treeLevels.Add(node.Right, level + 1);
                        trees.Enqueue(node.Right);
                    }
                }
                foreach (Tree node in treeLevels.Keys)
                {
                    int level = treeLevels[node];
                    levels[level] += node.data;
                }

            }
    }

I think your code is good.

As an alternative, you can use BFS search: http://en.wikipedia.org/wiki/Breadth-first_search. Here is sample C# code

    class Tree
    {
        public int data;
        public Tree Left;
        public Tree Right;


            static int[] levels = new int[100];

            static void EachLevelSum(Tree root)
            {
                // keeps track of each tree node's level
                Dictionary<Tree, int> treeLevels = new Dictionary<Tree,int>();
                treeLevels.Add(root, 0);

                // Do a BFS search and update the level of each node
                Queue<Tree> trees = new Queue<Tree>();
                trees.Enqueue(root);

                while (trees.Count != 0)
                {
                    Tree node = trees.Dequeue();
                    int level = treeLevels[node];
                    if (node.Left != null)
                    {
                        treeLevels.Add(node.Left, level + 1);
                        trees.Enqueue(node.Left);
                    }
                    if (node.Right != null)
                    {
                        treeLevels.Add(node.Right, level + 1);
                        trees.Enqueue(node.Right);
                    }
                }
                foreach (Tree node in treeLevels.Keys)
                {
                    int level = treeLevels[node];
                    levels[level] += node.data;
                }

            }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文