📜  打印给定 n 元树的节点列表,其子节点数在 [0, n] 范围内

📅  最后修改于: 2022-05-13 01:56:06.203000             🧑  作者: Mango

打印给定 n 元树的节点列表,其子节点数在 [0, n] 范围内

给定一个具有从 1 到 N 编号的N个节点的 n 叉树,任务是打印包含 0、1、2、3、...的节点列表。 . ., n 个孩子。

注意: n叉树是其中节点最多可以有n个子节点的树。

例子

方法:通过使用级别顺序遍历迭代树来解决问题的想法。

请按照以下步骤解决问题:

  • i = 1 遍历到 N:
    • 对于每个节点,使用级别顺序遍历来查找该值在树中的位置。
    • 找到该节点后,使用子节点列表并计算其拥有的子节点数(例如X )。
    • 使用映射第 i 个节点添加到具有X个子节点的节点列表中。
  • 迭代地图并打印子节点数量在 [0 到 n] 范围内的节点。

以下是上述方法的实现:

C++
// C++ code for the above approach:
  
#include 
using namespace std;
  
// Node Class
class Node {
public:
    int key_ele;
    vector child;
  
    Node(int data_value)
    {
        key_ele = data_value;
    }
};
  
// Function to find number of child
int numberOfChild(Node* root, int ele)
{
    int num = 0;
  
    if (root == NULL) {
        return 0;
    }
  
    // Initializing queue data structure
    queue q;
    q.push(root);
  
    while (!q.empty()) {
        int n = q.size();
        while (n > 0) {
            Node* nn = q.front();
            q.pop();
            if (nn->key_ele == ele) {
                num = num + nn->child.size();
                return num;
            }
            for (int i = 0;
                 i < nn->child.size(); i++) {
                q.push(nn->child[i]);
            }
            n--;
        }
    }
    return num;
}
  
// Function to print the nodes
// having children in range [0, n]
void printTree(Node* root, vector vec)
{
    // map to store nodes
    // with same number of children
    map > mp;
    int i = 0;
    for (i = 0; i < vec.size(); i++) {
        int temp;
        temp = numberOfChild(root, vec[i]);
        mp[temp].push_back(vec[i]);
    }
    map::iterator iter;
    for (auto& value : mp) {
        cout << value.first << " child: ";
        auto& list = value.second;
        int len = list.size();
        int s = 0;
        for (auto& element : list) {
            if (s < len - 1) {
                cout << element << ", ";
            }
            else {
                cout << element;
            }
            s++;
        }
        cout << endl;
    }
}
  
// Driver Code
int main()
{
    vector vec = { 1, 2, 3, 4, 5, 6, 7 };
    map > mp;
    vector v;
    Node* root = new Node(1);
    (root->child).push_back(new Node(2));
    (root->child).push_back(new Node(3));
    (root->child).push_back(new Node(4));
    (root->child[0]->child).push_back(new Node(5));
    (root->child[0]->child).push_back(new Node(6));
    (root->child[2]->child).push_back(new Node(7));
  
    // Function call
    printTree(root, vec);
  
    return 0;
}


输出
0 child: 3, 5, 6, 7
1 child: 4
2 child: 2
3 child: 1

时间复杂度: O(N 2 )
辅助空间: O(N)