C++ N叉树的实现

C++ N叉树的实现

参考:https://www.cnblogs.com/muxuan/p/ntree.html

 

#include <iostream>
#include <string>
#include <vector>
#include <queue>

using namespace std;

typedef struct MNode {
    int data;
    vector<MNode*> children;
    MNode * parent;
}MNode;

class MTree
{
private:
    MNode* root;
public:
    void init(MNode* root);
    void putChild(MNode * node, MNode* parent);
    void putChildren(vector<MNode *>nodes, MNode* parent);
    void transversal(MNode * root);
    void transversal();
    void traval(MNode * root);
};

void MTree::init(MNode *root)
{
    this->root = root;
}

void MTree::putChild(MNode* node, MNode * parent)
{
    parent->children.push_back(node);
    node->parent = parent;
}

void MTree::putChildren(vector<MNode *> nodes, MNode* parent)
{
    for (int i = 0; i < nodes.size(); i++)
    {
        putChild(nodes[i], parent);
    }
}

void MTree::transversal()
{
    this->transversal(this->root);
}

void MTree::transversal(MNode* root)
//后根遍历
{
    vector<MNode*> nodes = root->children;
    for (int i = 0; i < nodes.size(); i++)
    {
        if (nodes[i]->children.size() > 0)
        {
            transversal(nodes[i]);
        }
        else
        {
            cout << nodes[i]->data << ",";
        }
    }
    cout << root->data << ",";
}

void MTree::traval(MNode * root)
//层次遍历
{
    if (root == nullptr)
    {
        return;
    }
    queue<MNode*> que;
    que.push(root);

    while (!que.empty())
    {
        MNode* cur = que.front();
        que.pop();
        if (cur)
        {
            for (int i = 0; i < cur->children.size(); i++)
            {
                que.push(cur->children[i]);
            }
        }
        cout << cur->data << " ";
    }
}

int main()
{
    MNode node;
    MTree tree;
    node.parent = nullptr;
    node.data = 1;
    tree.init(&node);
    ///test nodes
    MNode node2, node3, node4, node5, node6, node7, node8, node9, node10;
    node2.data = 2, node3.data = 3, node4.data = 4, node5.data = 5, node6.data = 6;
    node7.data = 7, node8.data = 8, node9.data = 9, node10.data = 10;
    tree.putChild(&node2, &node), tree.putChild(&node3, &node), tree.putChild(&node4, &node);
    tree.putChild(&node5, &node3);
    tree.putChild(&node6, &node4), tree.putChild(&node7, &node4);
    tree.putChild(&node8, &node5), tree.putChild(&node9, &node5);
    tree.putChild(&node10, &node8);
    tree.transversal();
    cout << endl;
    cout << "*****************" << endl;
    tree.traval(&node);

    system("pause");
    return 0;
}

 

posted @ 2020-10-25 16:25  r1-12king  阅读(590)  评论(0编辑  收藏  举报