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;

}

效果展示

相关推荐

  1. leetcode中递归方式实现

    2024-02-05 19:36:01       51 阅读
  2. leetcode中迭代方式实现

    2024-02-05 19:36:01       60 阅读
  3. 方式非递归

    2024-02-05 19:36:01       35 阅读
  4. C语言

    2024-02-05 19:36:01       46 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-05 19:36:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-05 19:36:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-02-05 19:36:01       82 阅读
  4. Python语言-面向对象

    2024-02-05 19:36:01       91 阅读

热门阅读

  1. AI智能电销机器人有哪方面的技术优势?

    2024-02-05 19:36:01       46 阅读
  2. 网络安全-端口扫描和服务识别的几种方式

    2024-02-05 19:36:01       60 阅读
  3. Python——字节串bytes的编解码

    2024-02-05 19:36:01       55 阅读
  4. Django_基本增删改查

    2024-02-05 19:36:01       46 阅读
  5. C语言——教师信息管理系统

    2024-02-05 19:36:01       44 阅读
  6. 在(龙芯 3A6000)loongnix下编译syncthing

    2024-02-05 19:36:01       54 阅读
  7. 01环境准备

    2024-02-05 19:36:01       57 阅读