Re: Traversing and removing an element of a tree
Hi Tom,
Thank you for your reply. Here is the complete source code for the two
classes I've mentioned before.
Hope this will give you some clue, if it doesn't can I contact you
directly through your email?
// TTree.h: interface for the CTTree class.
//
//////////////////////////////////////////////////////////////////////
#if !
defined(AFX_TTREE_H__2F6E88C5_DE5E_4DEB_9748_D2A4B497A3AD__INCLUDED_)
#define AFX_TTREE_H__2F6E88C5_DE5E_4DEB_9748_D2A4B497A3AD__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CTTreeNode //transaction tree node
{
public:
CTTreeNode();
CTTreeNode(int s, CTTreeNode *p);
~CTTreeNode();
int id;
int count;
set<CTTreeNode> *children;
CTTreeNode *parent;
bool operator< (const CTTreeNode &tn) const {return id < tn.id;}
};
class CTTree //transaction tree
{
public:
CTTree();
virtual ~CTTree();
void processTransaction(Transaction *t);
set<CTTreeNode> *root;
void print(FILE *out);
void printRecur(set<CTTreeNode>::iterator it, FILE* out);
};
#endif // !
defined(AFX_TTREE_H__2F6E88C5_DE5E_4DEB_9748_D2A4B497A3AD__INCLUDED_)
// TTree.cpp: implementation of the CTTree class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "data.h"
#include <iostream>
#include <stdio.h>
#include <set>
using namespace std;
#include "TTree.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CTTreeNode::CTTreeNode()
{
count = 0;
parent = 0;
id = 0;
children = 0;
}
CTTreeNode::~CTTreeNode()
{
}
CTTreeNode::CTTreeNode(int s, CTTreeNode *p)
{
id = s;
parent = p;
count = 0;
children = 0;
}
CTTree::CTTree()
{
root = new set<CTTreeNode>;
CTTreeNode rootnode(0, 0);
rootnode.children = new set<CTTreeNode>();
root->insert(rootnode);
}
CTTree::~CTTree()
{
set<CTTreeNode>::iterator it;
for(it = root->begin(); it != root->end(); it++) {
if(it->children != 0)
delete it->children;
}
delete root;
}
void CTTree::processTransaction(Transaction *t)
{
set<CTTreeNode>::iterator it;
set<CTTreeNode>* nodes = root->begin()->children;
CTTreeNode *current = 0;
for(int depth=0; depth < t->length; depth++) {
it = nodes->insert(CTTreeNode(t->t[depth], current)).first;//
because insert check first
it->count++;
current = &(*it);
if(it->children==0)
it->children = new set<CTTreeNode>;
nodes = it->children;
}
}
void CTTree::print(FILE* out)
{
set<CTTreeNode>::iterator it = root->begin();
printRecur(it, out);
}
void CTTree::printRecur(set<CTTreeNode>::iterator it, FILE* out)
{
fprintf(out, "%d, %d\n", it->id, it->count);
//cout << it->id << ", " << it->count << endl;
set<CTTreeNode> *children = it->children;
for(set<CTTreeNode>::iterator itC=children->begin(); itC != children-
end(); itC++)
printRecur(itC, out);
}