
09-Aug-2005, 06:23
|
|
New Member
|
|
Join Date: May 2004
Posts: 20
|
|
|
Pointers problem
im making a binary tree program but got stuck at insertion funtion, though i have implemented this function using while loop but now im trying to do same with a recursive function....the problem is that in recursive function im passing the pointer of a node but don know y function isnt taking the argument correctly and make pointer = NULL?!? the source code is below:
#include<iostream>
using namespace std;
class treeNode
{
public:
treeNode* right;
treeNode* left;
int keyValue;
treeNode():right(NULL),left(NULL)
{ }
};
class BinaryTree
{
private:
treeNode* root, *ptr;
int itr;
public:
BinaryTree():root(NULL),ptr(NULL) //constructor
{ itr=1; }
void insert(int value); //function to add nodes
void checkList(treeNode*, treeNode*, int); //recursive func. which isn't working correctly
void inOrder(treeNode* ptr);
void traverse()
{ inOrder(root); }
};
//---------------------------------------------------------
void BinaryTree::inOrder(treeNode* ptr)
{
if( ptr == NULL )
return;
inOrder(ptr->left);
cout<<ptr->keyValue<<endl;
inOrder(ptr->right);
}
//---------------------------------------------------------
void BinaryTree::checkList(treeNode* myPtr, treeNode* newNode, int value)
{
/* when prog call this function, this func make myPtr = NULL */
/* though it is assigning value to newNode correctly */
treeNode* previous = myPtr;
if( myPtr != NULL )
{
if( myPtr->keyValue > value )
checkList(myPtr->left,newNode,value);
else
checkList(myPtr->right,newNode,value);
}
cout<<"Previous: "<<previous->keyValue<<endl;
if( value<previous->keyValue )
previous->left = newNode;
else
previous->left = newNode;
}
//---------------------------------------------------------
void BinaryTree::insert(int value)
{
cout<<"Iteration: "<<itr++<<endl;
treeNode* newNode = new treeNode;
newNode->keyValue = value;
ptr = root;
if( root == NULL )
{
root = newNode;
return;
}
else
checkList(ptr,newNode,value);
}
//---------------------------------------------------------
void main()
{
BinaryTree myTree;
myTree.insert(13);
myTree.insert(16);
myTree.insert(15);
myTree.insert(14);
myTree.traverse();
}
Last edited by LuciWiz : 09-Aug-2005 at 06:27.
Reason: Please insert your C++ code between [c++] & [/c++] tags
|