使用级别顺序

时间:2018-04-10 11:37:48

标签: c algorithm data-structures tree queue

给定结构:

struct node {
int data;
struct node *next;
struct node *child;
};

如何逐层添加n-Ary树中的元素?这背后的原因是我想让我的树完整或接近完成。

可以使用任何形式的帮助,提示,建议。

用户将输入数字n,这意味着每个节点都可以拥有多个子节点,而不是大于此节点。问题是,我只知道在之后添加root和前n个元素。我不知道如何回到root之后的第一个元素,所以我现在可以把其他节点作为他的孩子等等。

Root -> NULL
 |
 V
Child-1.1 -> Child-1.2 -> ... -> Child-1.n -> NULL
 |              |                   |            
 |              V                   V
 |              ...              Child-1.n.1 -> ... -> NULL
 V
Child-1.1.1 -> Child-1.1.2 -> ... -> NULL
 |
 ... etc

1 个答案:

答案 0 :(得分:0)

在您的代码中,您检查左右儿童,因为您只有两个:

if(temp -> left != NULL){
    Q = insertQ(Q, temp -> left);
}
else{
    temp -> left = newNode;
    free(Q);
    return root;
}

if(temp -> right != NULL){
    Q = insertQ(Q, temp -> right);
}
else{
    temp -> right = newNode;
    free(Q);
    return root;
    }
}

您现在需要做的是使用下一个指针进行迭代,并确保您达到n。类似的东西:

for (int i = 1 ; i < n; ++i, temp = temp->next) {
  if (temp->child) Q = insertQ(Q, temp->child);
  if (!(temp->next) && i < n-1) {
    // You don't have n nodes yet, so add the padding.
    temp->next = new Node;
  }
}
相关问题