1. 程式人生 > 實用技巧 >C++ N叉樹的實現

C++ N叉樹的實現

C++ N叉樹的實現

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

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

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 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 << ","; } 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(); system("pause"); return 0; }