Click here to Skip to main content
15,887,485 members
Articles / Desktop Programming / MFC
Article

An STL like Tree Class

Rate me:
Please Sign up or sign in to vote.
4.13/5 (14 votes)
28 May 20021 min read 112.2K   1.7K   34   20
A multi-node Tree class by using map and vector

Sample Image

Introduction

For more than a year and a half I have had to use some kind of multi-node tree to do something. However, all I found from the Internet are binary trees or equivalents. I therefore decided to write my own. Because I had to finish it pretty fast, I spent only two days for it, so it may be buggy.

In the project, it has three classes working like in STL container-iterator style.
template <class Key, class T> class Tree
template <class Key, class T> class Tree_iterator
template <class Key, class T> class TreeNode

A tree contains many tree nodes, while tree nodes contain data. Tree nodes of a tree are called children. In the design each node is assigned a level and the root node is of level 1. Tree_iterator is for navigation within the tree. Two tree-walk styles are defined. One walks down from the root node, while the other one use post-style to walk through all children of the tree. For each walk action, a

tree_iterator
is returned, so the user can use the iterator to reference the tree node and get the data.

I wrapped all the classes under the namespace Tiffany. For example, declaration of the tree with key type of wstring, and node data type of string, and add two levels of element is like:

Tiffany::Tree<wstring, string> x(L"Node 1", "Root");

px = x.AddChild(L"Key1","A");
px1 = x.AddChild(px, L"Key2", "1");

For a walk down action, you can limit it to a part of a tree ("sub-tree") by using the function SetSubTreePivot(px), and you can set the pivot to point back to the root node by calling SetWalkDownRootPivot. Try it out!. You can even delete part of the tree by calling DelSubTree().

Unfortunately I didn't have much time to prepare this document, but it should be obvious how to the classes.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Hong Kong Hong Kong
I'm a guy situated in Hong Kong with some knowledges in Java, VC++, C#, database, client-server, distributed, and mutithreaded computing and so on. I've been working in various companies as engineer, consultant, programmer.

Lately I was mainly working in banking & financial industries. Personally, I'm working on a trading application on my own now.

Comments and Discussions

 
Generalremove node Pin
filippov.anton25-Sep-07 1:35
filippov.anton25-Sep-07 1:35 
QuestionHow to delete a leaf-node? Pin
caijianshan17-Oct-06 21:46
caijianshan17-Oct-06 21:46 
GeneralInteresting Solution Pin
Dave Handley13-Aug-04 12:24
Dave Handley13-Aug-04 12:24 
GeneralRe: Interesting Solution Pin
Anonymous13-Aug-04 18:12
Anonymous13-Aug-04 18:12 
GeneralRe: Interesting Solution Pin
Dave Handley14-Aug-04 0:48
Dave Handley14-Aug-04 0:48 
GeneralRe: Interesting Solution Pin
rajas1-Sep-04 6:59
rajas1-Sep-04 6:59 
GeneralRe: Interesting Solution Pin
Dave Handley1-Sep-04 9:58
Dave Handley1-Sep-04 9:58 
Questionnot work in VC.net 2003? Pin
lad5-Aug-04 23:44
lad5-Aug-04 23:44 
AnswerRe: not work in VC.net 2003? Pin
Jovan Cakic24-Oct-04 11:34
Jovan Cakic24-Oct-04 11:34 
GeneralRe: not work in VC.net 2003? Pin
Scott McCain1-Jun-06 16:50
Scott McCain1-Jun-06 16:50 
Generaliterator AddChild (const Key parent, const Key nm, const T x) Pin
Member 60974615-Jan-04 18:15
Member 60974615-Jan-04 18:15 
GeneralRe: Sample Test Pin
Member 60974615-Jan-04 18:21
Member 60974615-Jan-04 18:21 
Questionmanaged C++? Pin
K2O328-Jul-03 11:56
K2O328-Jul-03 11:56 
QuestionDo you have a C# version of this? Pin
fetcher27-Jul-03 7:08
fetcher27-Jul-03 7:08 
AnswerRe: Do you have a C# version of this? Pin
Jack Hui27-Jul-03 7:30
Jack Hui27-Jul-03 7:30 
GeneralMoving nodes Pin
suzz..8-Aug-02 20:39
susssuzz..8-Aug-02 20:39 
GeneralRe: Moving nodes Pin
Anonymous9-Aug-02 20:29
Anonymous9-Aug-02 20:29 
Okay, I've added a new MoveSubTree function.

You can use it as:

//move from subtree [b] to under [g]
px1 = x.find(L"Key4");
px2 = x.find(L"Key16");
x.MoveSubTree(px2, px1);

x.SetWalkDownRootPivot();

cout << "After moving tree" << endl;

cout << "Data is: " << x.SubTreeGetData().c_str() << endl;

for (int i=1; i<17; i++) {
    x.SubTreeWalkDown();
    cout << "Data is: " << x.SubTreeGetData().c_str() << endl;


The new CPP file is here.

#ifndef _TREE_H_
#define _TREE_H_

/* 
Copyright - All copyright is owned by Mr Jack Hui
Author : Jack, Hui Ho Yin
Email : jackhui@hotmail.com, jackhui@hongkong.com
Update : 27-Aug-2000, 10-Aug-2002

*/

#pragma warning(disable : 4786) //debug info - name too long

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

using namespace std;

namespace Tiffany {

//forward declarations
template <class Key, class T> class TreeNode;
template <class Key, class T> class Tree;
template <class Key, class T> class Tree_iterator;
//


template <class Key, class T> class TreeNode
{
	friend class Tree<Key, T>;

protected:

	T						m_data;		//things stored in treenode
	Key						m_key;		//key to locate myself
	int						m_level;	//rootnode is of level 1

	TreeNode<Key,T>*			m_parent;	//points to node of parent
	vector<TreeNode<Key,T> *>	m_children;	//holds pointers for children

	vector<TreeNode<Key,T> *>::iterator	m_current;	//holds iterator to current child processing

	Tree<Key, T>*	m_LinkedTree;	//whom i'm belonging to

public:

    TreeNode(Tree<Key,T>* tr) : m_parent(NULL) {
		m_LinkedTree = tr;
	};
	
	TreeNode(Tree<Key,T>* tr, const Key key, const T x)	{
		m_key = key;
		m_data = x;
		m_LinkedTree = tr;
	};

	//Delete all the children of this node including all the down levels
    void DeleteAllChildren()	{

		vector<TreeNode<Key,T>*>::iterator		pchild;
		map<Key, TreeNode<Key,T>*>::iterator	itrmap;

		for(pchild=m_children.begin();pchild != m_children.end();)
		{
			(*pchild)->DeleteAllChildren();
			itrmap = m_LinkedTree->m_nodemap.find((*pchild)->m_key);

			m_LinkedTree->m_nodemap.erase(itrmap);
			delete *pchild;				//delete the TreeNode

			m_children.erase(pchild);
			//after removing the node, iterater is advanced
		}
	};

	//It erases a child from a Node without delete the node, and without remove
	//linking from the tree, so it can still be accessed from the tree's find().
	void EraseChild(Tree_iterator<Key, T> &itr)
	{
		vector<TreeNode<Key,T>*>::iterator		pchild;
		map<Key, TreeNode<Key,T>*>::iterator	itrmap;

		TreeNode<Key,T> *pNode = itr.m_Node->second;
		itrmap = m_LinkedTree->m_nodemap.find(pNode->m_key);

		//erase reference from the child vector
		for(pchild=m_children.begin();pchild != m_children.end(); pchild++)
		{
			if( (*pchild)->m_key == pNode->m_key)
			{
				m_children.erase(pchild);
				break;
			}
		}
	}

	//Return a reference to parent node in the tree
    TreeNode<Key,T>& GetParent () const {
		return *m_parent;
	};

	//returns a reference to vector to the children
    const vector<TreeNode<Key,T>*>& GetChildren () const
	{
		return  m_children;
	};
    
    long ChildCount () const
    {
		return m_children.size();
	};

	//add a child node to this node
    void AddChild (TreeNode<Key,T>* child)
	{
		child->m_parent = this;
		child->m_level = this->m_level + 1;
		m_children.push_back(child);
	};

	T GetData(void) const { return m_data; }
};


//************ End of Tree Node declaration ***************************//
//


//************ Start of Tree declaration ***************************//
//

template <class Key, class T>
class Tree {

	friend class TreeNode<Key, T>;

protected:

	//provide a name of the TreeNode to direct access to it
	map<Key, TreeNode<Key,T>*>		m_nodemap;		//a map for fast accessing TreeNode

    TreeNode<Key,T>*				m_pTreeroot;	//a pointer to root node

	TreeNode<Key,T>*				m_WalkPivot;	//Sub-tree root for walking

	TreeNode<Key,T>*				m_WalkCurrent;	//point to current node of walking

	TreeNode<Key,T>*				m_WalkParent;	//point to parent node of current node

public:

	typedef Tree_iterator<Key, T> iterator;

	typedef const iterator const_iterator;

	iterator begin() {
		iterator _tmp;
		_tmp.m_Node = m_nodemap.begin();

		return _tmp;
	}

	iterator end() {
		iterator _tmp;
		_tmp.m_Node = m_nodemap.end();

		return _tmp;
	}

	const_iterator begin() const {
		iterator _tmp;
		_tmp.m_Node = m_nodemap.begin();

		return _tmp;
	}

	const_iterator end() const {
		const_iterator _tmp;
		_tmp.m_Node = m_nodemap.end();

		return _tmp;
	}

	iterator find(const Key& key) {
		iterator _tmp;
		_tmp.m_Node = m_nodemap.find(key);

		return _tmp;
	}

	const_iterator find(const Key& key) const {
		const_iterator _tmp;
		_tmp.m_Node = m_nodemap.find(key);

		return _tmp;
	}

	Tree () : m_pTreeroot(NULL) {
		//instantiate an empty tree
	}

	Tree (const Key nm, const T x) {
		//instantiate a tree with the root node

		TreeNode<Key,T>* pNode;

		pNode = new TreeNode<Key,T>(this, nm, x);
		m_nodemap.insert(map<Key, TreeNode<Key,T>*>::value_type(nm, pNode));
		m_pTreeroot = pNode;
		pNode->m_level = 1;
	}

	~Tree()	{
		if (m_pTreeroot) {
			m_pTreeroot->DeleteAllChildren();
			delete m_pTreeroot;
		}
	}

	//returns tree root node, or NULL for empty tree
	TreeNode<Key,T>& GetRoot () const {
		return *m_pTreeroot;
	}
    
	iterator AddChild (iterator& parent, const Key nm, const T x) {
		TreeNode<Key,T>* pNew;

		pNew = new TreeNode<Key,T>(this, nm, x);
		parent.m_Node->second->AddChild(pNew);

		pair<map<Key, TreeNode<Key,T>*>::iterator, bool> pt = m_nodemap.insert(map<Key, TreeNode<Key,T>*>::value_type(nm, pNew));

		iterator _tmp;
		_tmp.m_Node = pt.first;
		return _tmp;
	}

    iterator AddChild (const Key nm, const T x) {
		TreeNode<Key,T>* pNew;

		pNew = new TreeNode<Key,T>(this, nm, x);

		m_pTreeroot->AddChild(pNew);

		pair<map<Key, TreeNode<Key,T>*>::iterator, bool> pt = m_nodemap.insert(map<Key, TreeNode<Key,T>*>::value_type(nm, pNew));

		iterator _tmp;
		_tmp.m_Node = pt.first;
		return _tmp;
	}

	void DeleteAllChildren(iterator & itr) {
		itr.m_Node->second->DeleteAllChildren();
	}

	size_t size(void) { return m_nodemap.size(); }

	//Set the sub-tree walking root and traverse to the first node
	void SetPostOrderSubTreePivot(iterator& it) {

		m_WalkPivot = it.m_Node->second;
		m_WalkCurrent = m_WalkPivot;
		m_WalkCurrent->m_current = m_WalkCurrent->m_children.begin();

		while (m_WalkCurrent->m_children.size() != 0) {
			m_WalkCurrent->m_current = m_WalkCurrent->m_children.begin();
			m_WalkCurrent = *(m_WalkCurrent->m_children.begin());
		}
		if (m_WalkCurrent != m_WalkPivot) {
			m_WalkParent = m_WalkCurrent->m_parent;
		}
		else {
			m_WalkParent = m_WalkCurrent;	//for the case no child in pivot
		}
	}

	//Set the sub-tree walking root and traverse to the first node
	void SetPostOrderRootPivot() {

		m_WalkPivot = m_pTreeroot;
		m_WalkCurrent = m_WalkPivot;
		m_WalkCurrent->m_current = m_WalkCurrent->m_children.begin();

		while (m_WalkCurrent->m_children.size() != 0) {
			m_WalkCurrent->m_current = m_WalkCurrent->m_children.begin();
			m_WalkCurrent = *(m_WalkCurrent->m_children.begin());
		}
		if (m_WalkCurrent != m_WalkPivot) {
			m_WalkParent = m_WalkCurrent->m_parent;
		}
		else {
			m_WalkParent = m_WalkCurrent;	//for the case no child in pivot
		}
	}

	//It sets root to be the pivot in Walk Down, first node is the first child
	void SetWalkDownSubTreePivot(iterator& itr) {

		m_WalkPivot = itr.m_Node->second;
		m_WalkCurrent = m_WalkPivot;
		m_WalkCurrent->m_current = m_WalkCurrent->m_children.begin();
	}


	//It sets root to be the pivot in Walk Down, first node is the first child
	void SetWalkDownRootPivot() {

		m_WalkPivot = m_pTreeroot;
		m_WalkCurrent = m_WalkPivot;
		m_WalkCurrent->m_current = m_WalkCurrent->m_children.begin();
	}

	//it advances m_WalkCurrent in post-order, and returns true if a move is made
	//else it returns false

	bool SubTreePostOrderWalk() {

		if (m_WalkCurrent == m_WalkPivot)
			return false;

		//if not the parent's last child, advance one node in paraent's child
		//if the advanced child contains sub node, go in depth to the leftmost one
		if (++m_WalkParent->m_current != m_WalkParent->m_children.end()) {
			m_WalkCurrent = *(m_WalkParent->m_current);
			while (m_WalkCurrent->m_children.size() != 0) {
				//go down
				m_WalkCurrent->m_current = m_WalkCurrent->m_children.begin();
				m_WalkParent = m_WalkCurrent;
				m_WalkCurrent = *(m_WalkCurrent->m_current);
			}
		}
		else {
			//if it's the last child of parent, we go up
			m_WalkCurrent = m_WalkParent;
			m_WalkParent = m_WalkCurrent->m_parent;
		}
		m_WalkParent = m_WalkCurrent->m_parent;

		return true;
	}

	//It advance the tree in top-down style with parent first
	bool SubTreeWalkDown() {

		//if it has children, we go down to children
		if (m_WalkCurrent->m_current != m_WalkCurrent->m_children.end()) {
			m_WalkCurrent = *(m_WalkCurrent->m_current);
			m_WalkParent = m_WalkCurrent->m_parent;
			m_WalkParent->m_current++;	//advance to next child for next iteration
			m_WalkCurrent->m_current = m_WalkCurrent->m_children.begin();	//initialize to first child
		}
		else {
			//if it's the last child of parent, we go up to the level
			//which we still need processing by recurively call ourself

			if (m_WalkCurrent == m_WalkPivot)
				return false;		//no more child
			m_WalkCurrent = m_WalkCurrent->m_parent;
			m_WalkParent = m_WalkCurrent->m_parent;
			SubTreeWalkDown();

		}
		return true;
	}

	void DelSubTree() {
	}

	//It moves a tree from source to destination. After moving a tree, tree walking will be invalid.
	//However iterator will still be valid. Users has to Set the new root pivot again.
	void MoveSubTree(iterator& dest_parent, iterator& src)
	{

		TreeNode<Key,T>* pSrcNode;
		TreeNode<Key,T>* pDestNode;
		TreeNode<Key,T>* pSrcNodeParent;

		pSrcNode = src.m_Node->second;
		pSrcNodeParent = pSrcNode->m_parent;

		//remove reference from original parent
		pSrcNodeParent->EraseChild(src);

		//add the src sub tree to destination parent node
		pDestNode = dest_parent.m_Node->second;
		pDestNode->AddChild(pSrcNode);

		iterator itr;
		itr = find(pSrcNode->m_key);

		//setting up correct level
		SetWalkDownSubTreePivot(itr);
		while (SubTreeWalkDown())
		{
			m_WalkCurrent->m_level = m_WalkCurrent->m_parent->m_level + 1;
		}

	}

	//It gets the current data while the tree is walking
	T SubTreeGetData(void) { return m_WalkCurrent->m_data; }

	//It gets the current node level while the tree is walking
	T SubTreeGetLevel(void) { return m_WalkCurrent->m_level; }

}; //class Tree

//************ End of Tree declaration ***************************//
//

//Actually, the interator is just a copy of the iterator to a std::map hold in
//the tree to provide simple navigation ability.
template <class Key, class T>
class Tree_iterator
{
	typedef map<Key, TreeNode<Key,T>*>::iterator _map_it;

	public:
		_map_it		m_Node;			//a (key, TreeNode *) iterator

		T operator*() const { return (m_Node->second)->GetData(); } 
		
		Tree_iterator& operator++()	{ 
			m_Node++;
			return *this; 
		}

		Tree_iterator operator++(int) {
			Tree_iterator __tmp = *this;
			m_Node++;
			return __tmp;
		}
    
		Tree_iterator& operator--() { 
			m_Node--;
			return *this; 
		}

		bool operator==(const Tree_iterator& _y) const {
			return m_Node == _y.m_Node;
		}

		bool operator!=(const Tree_iterator& _y) const {
			return m_Node != _y.m_Node;
		}

};	//class Tree_iterator

}; //namespace Tiffany

#endif //_TREE_H_

GeneralRe: Moving nodes Pin
29-Jul-03 20:52
suss29-Jul-03 20:52 
Questionwhy take chances with bugs? Pin
mystro_AKA_kokie29-May-02 18:55
mystro_AKA_kokie29-May-02 18:55 
AnswerRe: why take chances with bugs? Pin
31-May-02 17:26
suss31-May-02 17:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.