c语言二叉树的创建,三种遍历方式,销毁

二叉树的创建

typedef char datatype;
typedef struct Node
{
  datatype data;
  struct Node *left_child;
  struct Node *right_child;

}*Btree;
//二叉树的创建
Btree create_node()
{
  Btree t=(Btree)malloc(sizeof(struct Node));
  if(NULL==t)
    return NULL;
  t->data=0;
  t->left_child=t->right_child=NULL;
  return t;
}
//c语言模拟二叉树的建立
Btree create_tree()
{
   datatype element;
   printf("INPUT:");
   scanf(" %c",&element);
   if(element=='#')
      return NULL;
   Btree tree=create_node();
   tree->data=element;
   puts("LEFT");
   tree->left_child=create_tree();
   puts("RIGHT");
   tree->right_child=create_tree();
   return tree;
}

前序遍历

//二叉树的先序遍历  根左右
void frist_output(Btree tree)
{
    if(NULL==tree)
	{
		return ;
	}
	printf("%c",tree->data);
    frist_output(tree->left_child);
	frist_output(tree->right_child);
}

中序遍历

//二叉树的中序遍历 左根右
void mid_output(Btree tree)
{
	if(NULL==tree)
	{
	  return ;
	}
	mid_output(tree->left_child);
	printf("%c",tree->data);
	mid_output(tree->right_child);  
}

后序遍历

//二叉树的后序遍历 左右根
void last_output(Btree tree)
{
    if(NULL==tree)
	{
	  return;
	}
	last_output(tree->left_child);
	last_output(tree->right_child);
	printf("%c",tree->data);
}

销毁二叉树

//二叉树的销毁
void free_tree(Btree tree)
{
 if(NULL==tree)
 {
   return;
 }
 free_tree(tree->left_child);
 free_tree(tree->right_child);
 free(tree);
 tree=NULL;

}

效果展示

c语言二叉树的创建,三种遍历方式,销毁_第1张图片

你可能感兴趣的:(c语言,数据结构)