C++自定义树结构模板

借助vector定义了一个简单的树数据结构,由于后面没有用到,也没有进一步优化。如果不十分在意效率问题,勉强可以用。

///Tree.h 文件
#pragma once
#include <vector>
#include <string>
#include <algorithm>
using std::vector;
using std::string;
 
 
template<typename Type>
class CTree
{
public:
	Type node;
	Type father;
	vector< CTree > children;
 
	CTree(const Type & root)
	{
		this->node=root;
		this->father=NULL;
	}
 
	CTree()
	{
		this->father=NULL;
	}
 
	void AddChild(CTree child)
	{
		child.father=(this->node);
		children.push_back(child);
	}
 
	void AddChild(Type node)
	{
		CTree addTree=CTree(node);
		addTree.father=this->node;
		children.push_back(addTree);
	}
 
	~CTree()
	{
 
	}
 
	void PrintTree()
	{
		cout<<node<<endl;
 
		vector< CTree > eachNodeChildren = this->children;
		for ( auto it = eachNodeChildren.begin() ; it != eachNodeChildren.end() ; it++ )
		{
			it->PrintTree();
		}
	}
};

  

posted @ 2020-11-17 08:44  originalcandy  阅读(264)  评论(0编辑  收藏  举报