1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
#include<iostream>
using namespace std;
int nodeCount;
struct TNode
{
int data;
TNode* left;
TNode* right;
};
// Take integer, create new node, and return address of new node
TNode* GetNewNode(int data)
{
TNode* newNode = new TNode(); //Define newNode as a pointer, create new memory block, assign newNode to that block
newNode->data = data; //Takes the data passed into the function and copies it to the data field in the new node
// (*newNode) "newNode is dereferenced" .data = data; Dereferencing gives you a value. Assign this value "data" as into the new field!
newNode->left = NULL; //Default value is NULL, or 0.
newNode->right = NULL;
return newNode; //Returns address of new node
}
TNode* Insert(TNode* root, int data) //Note how 'root' is a local variable and the address of the root.
{
if(root == NULL)
{
root = GetNewNode(data);
nodeCount++;
return root;
}
else if(data <= root->data) //If the new data 'data' is less than or equal to the older data 'root->data'
{
root->left = Insert(root->left, data); //Set left field of current node equal to the address of the new node
}
else if(data > root->data) //If the new data 'data' is greater than the older data 'root->data'
{
root->right = Insert(root->right, data); //Set right field of current node equal to the address of the new node
}
return root;
}
int main()
{
TNode* root = NULL; //Creating an empty tree
root = Insert(root, 15); //Note that we set the default address of 'root' to 0, or NULL
root = Insert(root, 10); //The second parameter, 'data' is the integer to be inserted
root = Insert(root, 20);
int number;
cout << "There are " << nodeCount << " nodes in this tree." << endl << endl;
cout << "Enter a number to be searched:" << endl;
cin >> number;
|