Thread: problem in creating a tree

  1. #1
    Registered User
    Join Date
    Mar 2005
    Location
    Hangzhou,China
    Posts
    7

    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. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    1. Don't cross-post
    2. Choose the right forum
    http://cboard.cprogramming.com/showthread.php?t=70135
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. BST delete again, but this time I think I'm close
    By tms43 in forum C++ Programming
    Replies: 9
    Last Post: 11-05-2006, 06:24 PM
  2. binary tree token problem
    By OldSchool in forum C++ Programming
    Replies: 13
    Last Post: 05-28-2006, 10:42 PM
  3. problem in creating a tree
    By Lorin_sz in forum C++ Programming
    Replies: 2
    Last Post: 09-26-2005, 01:28 PM
  4. searching and insertion in a binary search tree
    By galmca in forum C Programming
    Replies: 1
    Last Post: 03-26-2005, 05:15 PM
  5. Binary tree problem
    By carrja99 in forum C++ Programming
    Replies: 4
    Last Post: 02-27-2003, 09:36 PM