简体   繁体   English

使用级别顺序在n-Ary树中输入元素

[英]Input elements in n-Ary tree using Level order

Given structure: 给定结构:

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

How can I add elements in n-Ary tree level by level? 如何逐级在n-Ary树中添加元素? The reason behind this is that I want to make my tree complete or nearly complete. 这背后的原因是我想使我的树完整或接近完整。

Could use any form of help, hint, suggestion. 可以使用任何形式的帮助,提示,建议。

User will input number n, which means that every node can have that many children, not greater than that. 用户将输入数字n,这意味着每个节点可以具有那么多子节点,但不能大于该数目。 The problem is, I only know to add root and first n elements after. 问题是,我只知道在之后添加root和前n个元素。 I am not sure how to get back to the first element after root, so that I can now put other nodes as his children and so on. 我不确定如何返回到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

In your code you check left and right children because you only have two: 在代码中,您检查左右两个孩子,因为您只有两个:

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

What you need to do now is iterate using the next pointer and make sure you reach n. 您现在需要做的是使用下一个指针进行迭代,并确保到达n。 Something like: 就像是:

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

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

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