jim
BAN USER#include<stdio.h>
#include<stdlib.h>
struct node
{
int value;
struct node *left;
struct node *right;
};
void insert(struct node **temp,int key)
{
struct node *temp1=NULL;
if(*temp==NULL)
{
temp1=(struct node*)malloc(sizeof(struct node));
temp1->right=NULL;
temp1->left=NULL;
temp1->value=key;
*temp=temp1;
return;
}
if(((*temp)->value)<key)
{
insert(&(*temp)->right,key);
}
else if(((*temp)->value)>key)
{
insert(&(*temp)->left,key);
}
}
void preorder(struct node *temp)
{
if(temp!=NULL)
{
printf("%d\n",temp->value);
preorder(temp->left);
preorder(temp->right);
}
}
void print_zigzag(struct node *root)
{
int h=height(root);
int i,c=1;
for(i=1;i<h+1;i++)
{
c++;
zigzagorder(root,i,c);
}
}
void zigzagorder(struct node *root,int level,int c)
{
if(root==NULL)
return ;
if(level==1)
{
printf("%d\n",root->value);
}
else
{
if(c%2==0)
{
zigzagorder(root->left,level-1,c);
zigzagorder(root->right,level-1,c);
}
else
{
zigzagorder(root->right,level-1,c);
zigzagorder(root->left,level-1,c);
}
}
}
int height(struct node *node)
{
if (node==NULL)
return 0;
else
{
/* compute the height of each subtree */
int lheight = height(node->left);
int rheight = height(node->right);
/* use the larger one */
if (lheight > rheight)
return(lheight+1);
else return(rheight+1);
}
}
main()
{
struct node *root;
root=NULL;
printf("tree\n");
insert(&root,5);
insert(&root,10);
insert(&root,7);
//insert(&root,8);
insert(&root,3);
insert(&root,11);
insert(&root,2);
insert(&root,4);
insert(&root,1);
insert(&root,12);
//insert(&root,6);
printf("preorder:\n");
preorder(root);
printf("depth of tree is %d\n",height(root));
printf("print_zigzag:\n");
print_zigzag(root);
}
- jim June 28, 2014