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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
#include <iostream>
using namespace std;
struct TNode
{
int data;
TNode* left;
TNode* right;
TNode(int data, TNode* left = NULL, TNode* right = NULL);
TNode* Insert(int data);
};
TNode::TNode(int data, TNode* left, TNode* right)
{
this->data = data;
this->left = left;
this->right = right;
}
TNode* GetNewNode(int data)
{
TNode* newNode = new TNode(data, NULL, NULL);
return newNode;
}
TNode* Insert(TNode* root, int data)
{
if(root == NULL)
{
root = GetNewNode(data);
return root;
}
if(data <= root->data)
{
root->left = Insert(root->left, data);
}
else
{
root->right = Insert(root->right, data);
}
return root;
}
int treeSize(TNode* root)
{
if(root == NULL)
{
return 0;
}
else
{
return treeSize(root->left) + treeSize(root->right) + 1;
}
}
void inOrder(TNode* root)
{
if(root->left != NULL)
{
inOrder(root->left);
}
cout << root->data << " ";
if(root->right != NULL)
{
inOrder(root->right);
}
}
int main()
{
TNode* root = NULL;
root = Insert(root, 5);
Insert(root, 3);
Insert(root, 9);
Insert(root, 1);
Insert(root, 4);
Insert(root, 6);
inOrder(root);
cout << endl << "There are " << treeSize(root) << " nodes in this tree." << endl;
}
|