Skip to content

Instantly share code, notes, and snippets.

@kelvin-fly
Created September 11, 2012 00:59
Show Gist options
  • Select an option

  • Save kelvin-fly/3695193 to your computer and use it in GitHub Desktop.

Select an option

Save kelvin-fly/3695193 to your computer and use it in GitHub Desktop.
the basic of tree
#include <stdio.h>
#define MAXSIZE 100
typedef char DataType;
typedef struct Node
{
DataType data;
struct Node *left;
struct Node *right;
}BTNode, *PBTNode, *BiTreeLink;
BiTreeLink CreateBiTree(char *nodes, int pos, int num);
void DispBiTree(BiTreeLink root);
int main(char argc, char **argv)
{
BiTreeLink root;
int i;
char nodes[] = "RABCDE F G ";
root = CreateBiTree(nodes,1,15);
printf("please echo sequence number!\n");
for(i =1; i<16; i++)
printf("(%c)",nodes[i]);
printf("\n\n\nbinary tree output sequence number:\n");
DispBiTree(root);
return 0;
}
BiTreeLink CreateBiTree(char *nodes, int pos, int num)
{
PBTNode p;
if(nodes[pos]== ""||pos>num)
return NULL;
p = (PBTNode)malloc(sizeof(BTNode));
if(!p)
{
printf("initial link failed!!!\n");
return 0;
}
p->data = nodes[pos];
p->left = CreateBiTree(nodes,2*pos,num);
p->right = CreateBiTree(nodes,2*pos+1,num);
return p;
}
void DispBiTree(BiTreeLink root)
{
PBTNode queue[MAXSIZE];
int front,rear;
PBTNode p;
if(root == NULL)
return;
queue[0] = root;
front = 0;
rear = 1;
while(front < rear)
{
p = queue[front];
front = (front +1)%MAXSIZE;
if(p == NULL)
printf("()");
else
printf("(%c)",p->data);
if(p!=NULL)
{
queue[rear] = p->left;
rear = (rear+1)%MAXSIZE;
queue[rear] = p->right;
rear = (rear+1)%MAXSIZE;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment