0% found this document useful (0 votes)
14 views3 pages

Asm 5 0

This C++ program defines a binary tree node class and functions to create nodes, insert nodes, calculate the tree size, and display the tree using in-order traversal. It takes user input to build a binary search tree of integers, outputs the size, and displays the elements using in-order traversal.

Uploaded by

Shameer Ijaz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views3 pages

Asm 5 0

This C++ program defines a binary tree node class and functions to create nodes, insert nodes, calculate the tree size, and display the tree using in-order traversal. It takes user input to build a binary search tree of integers, outputs the size, and displays the elements using in-order traversal.

Uploaded by

Shameer Ijaz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

#

#include <iostream>
using namespace std;

class myNode
{
public:
int value;
myNode *leftChild;
myNode *rightChild;
};

myNode *createNode(int data)


{
myNode *newNode = new myNode();
newNode->value = data;
newNode->leftChild = NULL;
newNode->rightChild = NULL;

return newNode;
}

// inserting nodes
myNode *insertNode(myNode *root, int key)
{
if (root == NULL)
{
return createNode(key);
}
if (key < root->value)
{
root->leftChild = insertNode(root->leftChild, key);
}
else if (key > root->value)
{
root->rightChild = insertNode(root->rightChild, key);
}
return root;
}

// calculate size of tree


int calculateSize(myNode *node)
{
if (node == NULL)
{
return 0;
}
else
{
return (calculateSize(node->leftChild) + 1 + calculateSize(node-
>rightChild));
}
}

// print the tree


void displayTree(myNode *node)
{
if (node == NULL)
{
return;
}

// In-order traversal: Left, Root, Right


displayTree(node->leftChild);
cout << node->value << " ";
displayTree(node->rightChild);
}

int main()
{
system("cls");
myNode *treeRoot = NULL;
int num, numValues;

cout << "Enter the number of nodes: ";


cin >> numValues;

// get values to add in tree


for (int i = 0; i < numValues; ++i)
{
cout << "Enter value " << i + 1 << ": ";
cin >> num;
treeRoot = insertNode(treeRoot, num);
}

cout << "Size of tree: " << calculateSize(treeRoot) << endl;

cout << "Elements in the tree: ";


displayTree(treeRoot);

return 0;
}

You might also like