Hey guys I'm attempting to create a binary tree using pointers and then be able to do functions like post-order, pre-order, etc.
Anyways, I am having problems with getting the functions to work with a user input. I'm relatively new to structs, but I think from the tutorials I have read this is formatted relatively correctly. If anyone knows why my main functions isn't accepting the inputs/functions that I have created that would be awesome. Thanks for any responses you can give me :)
#include <iostream>
#include <cstdlib>
using namespace std;
struct Node
{
int data;
Node* left;
Node* right;
};
class btree
{
public:
btree();
void insert(int num);
Node *search(int num);
void btree::preorderWalk( Node *root );
void btree::inorderWalk( Node *root );
void btree::postorderWalk( Node *root );
private:
void insert(int num, Node *leaf);
Node *search(int num, Node *leaf);
Node *root;
};
btree::btree()
{
root=NULL;
}
void btree::insert(int num)
{
if(root!=NULL)
{
insert(num, root);
}
else
{
root=new Node;
root->data=num;
root->left=NULL;
root->right=NULL;
}
}
void btree::insert(int num, Node *leaf)
{
if(num< leaf->data)
{
if(leaf->left!=NULL)
{
insert(num, leaf->left);
}
else
{
leaf->left=new Node;
leaf->left->data=num;
leaf->left->left=NULL;
leaf->left->right=NULL;
}
}
else if(num>=leaf->data)
{
if(leaf->right!=NULL)
insert(num, leaf->right);
else
{
leaf->right=new Node;
leaf->right->data=num;
leaf->right->left=NULL;
leaf->right->right=NULL;
}
}
}
Node *btree::search(int num, Node *leaf)
{
if(leaf!=NULL)
{
if(num==leaf->data)
return leaf;
if(num<leaf->data)
return search(num, leaf->left);
else
return search(num, leaf->right);
}
else return NULL;
}
Node *btree::search(int num)
{
return search(num, root);
}
void btree::preorderWalk( Node *root )
{
if ( root != NULL )
{
cout << root->data << " ";
preorderWalk( root->left );
preorderWalk( root->right );
}
else
{
cout << "Tree is empty\n";
}
}
void btree::postorderWalk( Node *root )
{
if ( root != NULL )
{
postorderWalk( root->left );
postorderWalk( root->right );
cout << root->data << " ";
}
}
void btree::inorderWalk( Node *root )
{
if ( root != NULL )
{
inorderWalk( root->left );
cout << root->data << " ";
inorderWalk( root->right );
}
}
int main()
{
char menuchoice;
int binum;
cout << "Please enter a menu choice:\n";
cout << "'A' - In-order Print\n";
cout << "'B' - Pre-order Print\n";
cout << "'C' - Post-order Print\n";
cout << "'I' - Insert Command\n";
cout << "'S' - Search Command\n";
cout << "'D' - Delete Command\n";
cout << "'N' - Tree Minimum Command\n";
cout << "'Q' - Quit Program\n";
cin >> menuchoice;
if(menuchoice == 'I')
{
cout << "Enter a key to insert\n";
cin >> binum;
void btree::insert(binum);
cout << "The item inserted";
}
else if(menuchoice == 'A')
{
void btree::inorderWalk(root);
}
return 0;
}