Click here to Skip to main content
15,892,005 members
Articles / Programming Languages / Objective C

Tree Data Class for C++

Rate me:
Please Sign up or sign in to vote.
4.61/5 (14 votes)
12 Jan 20022 min read 215.2K   3.6K   51  
Simple class to represent tree data structures in C++
// treedemo.cpp : Defines the entry point for the console application.
//

#include "stdio.h"
#include "tree.h"
#include "string"
using namespace std;

typedef Tree<string> StringTree;
typedef StringTree::Node StringNode;


// recursive function for prionitng nodes
void PrintNode(StringNode node,int nLevel) {
	// print new line
	fputs("\n",stdout);
	// print spaces for indent (2 for every level)
	string s;
	s.resize(nLevel*2,' ');
	fputs(s.c_str(),stdout);

	// print the value
	fputs(node.get_Data()->c_str(),stdout);

	// iterate through children
	nLevel++;
	for(int n=0;n<node.Count;n++) {
		PrintNode(node.Nodes[n],nLevel);
	}
}

int main(int argc, char* argv[])
{
	// define the tree
	StringTree tree; 
	((string&)tree)="Root";

	//add few nodes
	StringNode node=tree;

	node.AddNode("1").AddNode("11");
	StringNode node2=node.AddNode("2");

	node2.AddNode("21").AddNode("211");
	node2.AddNode("22");
	node2.AddNode("23");
	
	node.AddNode("3");

	// print the tree
	PrintNode(tree,0);

	// wait for enter
	char buf[3];
	fputs("\nPress ENTER :",stdout);
	fgets(buf,3,stdin);
	return 0;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions