数据结构(树)

    科技2022-07-11  107

    // tNode.h #pragma once #include <iostream> #include <vector> #include <string> using namespace std; //************************************ // Method: TreeNode // FullName: TreeNode // Qualifier: 树节点属性 //************************************ class Property { public: //默认添加设置属性的方法 Property(int value, int num) { iValue = value; iChildNum = num; } //自定义添加设置属性的方法:TODO Property() { } //析构函数 ~Property() {} public: //初始化函数 void init() { setValue(); setChildNum(); } //自定义添加获取属性的方法:TODO //获取iValue的值 int getValue() { return iValue; } //获取ichildNum的值 int getChildNum() { return iChildNum; } protected: void setValue() { //键入节点数值 cout << "该节点的值为:" << endl; cin >> iValue; } void setChildNum() { //键入节点个数 cout << "该节点的子节点个数为:" << endl; cin >> iChildNum; } private: int iValue; int iChildNum; vector<int> viArrary; }; //************************************ // Method: TreeNode // FullName: TreeNode // Qualifier: 一棵树的节点 //************************************ struct TreeNode { vector<TreeNode*> vTChildren; Property* pNature; }; struct SumPara { vector<int> vecs; }; //************************************ // Method: CreateTree // FullName: CreateTree // Access: public // Returns: void // Qualifier: 创建一棵树 // Parameter: TreeNode * & tNode //************************************ void CreateTree(TreeNode*& tNode, SumPara sp) { //设置一个树节点的属性 Property* prop=new Property(); //如果节点输入的值为-1,该节点为空节点 if (prop->getValue() == -1) { return; } //设置当前节点的属性 tNode = new TreeNode; tNode->pNature = prop; prop->init(); tNode->vTChildren.resize(tNode->pNature->getChildNum(), NULL); //处理孩子节点 for (int i = 0; i < tNode->pNature->getChildNum(); ++i) { //递归处理子节点 CreateTree(tNode->vTChildren[i]); } } //************************************ // Method: VisitTree // FullName: VisitTree // Access: public // Returns: void // Qualifier: 先序遍历一棵树 // Parameter: TreeNode * tNode //************************************ void VisitTree(TreeNode* tNode) { if (!tNode) { return; } cout << tNode->pNature->getValue() << endl; int iSize = tNode->vTChildren.size(); for (int i = 0; i < iSize;++i) { VisitTree(tNode->vTChildren[i]); } } // main.cpp #include "tNode.h" void main() { TreeNode* tn = NULL; cout << "创建一棵树" << endl; CreateTree(tn); cout << "访问结果为:" << endl; VisitTree(tn); cout << "路径搜索为:" << endl; vector<TreeNode*> vPath; SeekMinCost(tn, vPath); system("pause"); }
    Processed: 0.029, SQL: 8