简体   繁体   English

C 二叉树叉深度和宽度

[英]C Binary Tree fork depth and width

I'm learning C and I'm stuck with fork function and processes.我正在学习 C 并且我坚持使用叉子 function 和进程。 I want to create a c program that gets 2 inputs (depth and width) to create the tree like in the image我想创建一个 c 程序,它获取 2 个输入(深度和宽度)来创建图像中的树

This is the code I have done now:这是我现在完成的代码:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include<sys/wait.h>

int
main (int argc, char *argv[])
{
  int i, depth, width, pid, j, pid2;

  if (argc != 3)
    exit (0);

  depth= atoi (argv[1]);
  width = atoi (argv[2]);

  for (i = 0; i < width; i++)
    {
      pid = fork ();
      if (pid < 0)
        {
          printf ("Error");
          exit (1);
        }
          else if (pid == 0)
        {
          for (j = 0; j < depth; j++)
            {
              pid2 = fork ();
              if (pid2 < 0)
                {
                  printf ("Error");
                  exit (1);
                }
                  else if (pid2 == 0)
                {
                  printf ("Child (%d): %d\n", j + 1, getpid ());
                  exit (0);
                }
                  else
                {
                  wait (NULL);
                }
            }
        }
          else
        {
          wait (NULL);
        }
    }

  printf ("Child %d and parent %d\n", getpid (), getppid ());
  sleep (1);
  return 0;
}

First of all, you are misunderstanding the meaning of "width" and "depth" for a tree - your picture does not represent a tree of width 2 and depth 3. Your picture shows only a part of a tree of width 2, not the whole tree;首先,您误解了树的“宽度”和“深度”的含义-您的图片不代表宽度为2和深度为3的树。您的图片仅显示宽度为2的树的一部分,而不是整棵树; and, in your picture the depth of the tree is 2, not 3. Grok this stuff first.而且,在您的图片中,树的深度是 2,而不是 3。先了解这些东西。

After you understand trees, you are ready to implement one with a single process (forget fork for now).在你理解了树之后,你就可以用一个进程来实现树了(暂时忘记fork )。

You can't implement a tree with 2 nested loops, one for width, one for depth.您无法实现具有 2 个嵌套循环的树,一个用于宽度,一个用于深度。 You can use a for loop for width, but you have to use recursion for the depth.您可以使用for循环来获取宽度,但您必须使用递归来获取深度。 The recursive function has depth as parameter, and when you call it again, you increment the parameter.递归 function 有深度作为参数,当你再次调用它时,你增加了参数。

OK, once you figure that out, then add forking.好的,一旦你弄清楚了,然后添加分叉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM