Hi,
I've question regarding visiting and printing nodes for tree traversal.

the main purpose of my program is to create tree for an arithmetic expression and then perform in-order and post-order traversal on the tree.

The structure tree need to be hard-coded in the program using linked-list/pointer stored in one function.

this is what i did:

#include <iostream>

using namespace std;

class Tree{
	private:
	char data;
	Tree *leftptr, *rightptr;
	
	public:
	Tree(char newthing, Tree *L, Tree *R);
	~Tree() { };
	char RootData() { return data;}
	Tree *Left() {return leftptr;}
	Tree *Right() {return rightptr;}
	void Setup();
	void inorder(Tree *T);
};

Tree::Tree(char newthing, Tree *L, Tree *R){
	data = newthing;
	leftptr = L;
	rightptr = R;
}

Tree *T1, *T2, *T3, *T4, *T5;

/*void Tree:: Setup(){
	T1 = new Tree(2, NULL, NULL);
	T2 = new Tree(3, NULL, NULL);
	T3 = new Tree(5, NULL, NULL);
	T4 = new Tree('*', T2, T3);
	T5 = new Tree('+', T4, T1);
}*/

void Tree::inorder(Tree *T){
	if(T==NULL){ return;}
	inorder(T->Left());
	cout << T-> RootData();
	inorder(T-> Right());
}

int main(){
	Tree *root;
	root = NULL;
	root.inorder(T5);
	
}

my question is:
1. How do you relate the tree that i've setup in Setup() to main? and i am not sure if i set it up the right way.

2. how do you load the tree to perform inorder traversal?

Thanks heaps for your help, any suggestions welcome xD

I think if you have this as main(), and remove the setup function as a member of the class.

int main ( ) {
	Tree *T1, *T2, *T3, *T4, *T5;
	T1 = new Tree(2, NULL, NULL);
	T2 = new Tree(3, NULL, NULL);
	T3 = new Tree(5, NULL, NULL);
	T4 = new Tree('*', T2, T3);
	T5 = new Tree('+', T4, T1);
	T5->inorder(T5);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.