using namespace std;
struct Node
{
int data;
Node* left;
Node* right;
};
Node* ROOT = NULL;
int height(struct Node* node)
{
if (node==NULL)
return 0;
else
{
int lheight = height(node->left);
int rheight = height(node->right);
if (lheight > rheight)
return(lheight+1);
else return(rheight+1);
}
}
void printGivenLevel(struct Node* root, int level)
{
if(root == NULL)
return;
if(level == 1)
printf("%d ", root->data);
else if (level > 1)
{
printGivenLevel(root->left, level-1);
printGivenLevel(root->right, level-1);
}
}
void printLevelOrder(struct Node* root)
{
int h = height(root);
int i;
for(i=1; i<=h; i++)
printGivenLevel(root, i);
}
void add(int item)
{
Node* newNode = new Node;
newNode->data = item;
newNode->left = NULL;
newNode->right = NULL;
if(ROOT == NULL)
{
ROOT = newNode;
}
else
{
Node* t = ROOT;
while(true)
{
if(item <= t->data)
{
if(t->left == NULL)
{
t->left = newNode;
break;
}
else
{
t = t->left;
}
}
else
{
if(t->right == NULL)
{
t->right = newNode;
break;
}
else
{
t = t->right;
}
}
}
}
}
void print_inorder(Node* node)
{
if(node != NULL)
{
print_inorder(node->left);
cout << node->data << " ";
print_inorder(node->right);
}
}
void print_preorder(Node* node)
{
if(node != NULL)
{
cout << node->data << " ";
print_preorder(node->left);
print_preorder(node->right);
}
}
void print_postorder(Node* node)
{
if(node != NULL)
{
print_postorder(node->left);
print_postorder(node->right);
cout << node->data << " ";
}
}
int main()
{
add(50);
add(70);
add(25);
add(31);
add(21);
add(19);
add(42);
cout << endl;
print_inorder(ROOT);
cout << endl;
print_preorder(ROOT);
cout << endl;
print_postorder(ROOT);
cout << endl;
cout<<"Level Order";
printLevelOrder(ROOT);
return 0;
}
0 comments :
Post a Comment