# problem in creating a tree

This is a discussion on problem in creating a tree within the C++ Programming forums, part of the General Programming Boards category; Hi, I encountered some problems in creating a tree and using preorder algorithm to travel it. Code: // Create a ...

1. ## problem in creating a tree

Hi, I encountered some problems in creating a tree and using preorder algorithm to travel it.

Code:
```// Create a binary search tree

#include<iostream>
struct TreeNode;
typedef struct TreeNode *PtrToNode;
typedef struct TreeNode *Tree;
using namespace std;

struct TreeNode {
int data;
PtrToNode left;
PtrToNode right;
};

// insert a new node into a binary search tree
// using a recursive algorithm
void insert(Tree tree, int item) {
if( tree == 0 ) {
tree = (Tree)malloc(sizeof(struct TreeNode));
if( tree == 0 ) {
cout << "Fatal error!" << endl;
exit(1);
}
else {
tree->data = item;
tree->left = tree->right = 0;
}
}

else if( item < tree->data )
insert( tree->left, item);
else if( item > tree->data )
insert( tree->right, item );

}

// create a new binary search tree
void createTree( Tree tree, int a[], int n ) {
for( int i = 0; i < n; i++ )
insert( tree, a[i] );
}

void preorder( Tree tree ) {
if( tree != 0 ) {
cout << tree ->data << ' ';
preorder( tree->left );
preorder( tree->right );
}
}

int main(void) {
const int maxsize = 5;
int a[maxsize] = {5,3,9,1,10};
Tree T = 0;
createTree(T,a,maxsize);

preorder( T );

return 0;
}```
so why there is no output to the screen??
thanks for your help~~~

2. > tree = (Tree)malloc(sizeof(struct TreeNode));
Use new in C++, not malloc.

The main problem is you don't return the tree to main - remember, it's pass by value.
To fix this, make insert pass the tree by reference

3. You are passing the tree pointer by value to your createTree and insert functions. You should pass the pointers by reference so that the new pointer value created by the call to malloc will be saved in the original pointer variable passed to the function.

Note that you have to make createTree take a reference as well.

Popular pages Recent additions