二叉树的创建与遍历

绪论

二叉树是一种树形结构,其中每个节点最多有两个子节点,称左子节点与右子节点。每个节点最多有一个父节点,根节点0个

二叉树分为二叉搜索树,完全二叉树,平衡二叉树,红黑树等,

二叉树的建立可以有辅助队列法和递归法,二者各有优缺点

这里采用递归法

1.二叉树的创建

   #include<stdlib.h>
   #include<stdio.h>
   typedef struct node
            {
                   int data;
                   struct node *lchild;
                   struct node *rchild;
           }bintree;
  bintree* creat_bintree(int root, int n)
  {
          bintree* r = malloc(sizeof(bintree));
          if (r == NULL)
          {
                  perror("malloc");
                  return 0;
          }
          r->data = root;
          printf("root=%d\n", root);
          if (root<<1<=n)
          {
                  r->lchild = creat_bintree(root<<1, n);
                  
          }
          else
                  r->lchild = NULL;
          if ((1 + (root<<1))<=n)
          {
         
                  r->rchild = creat_bintree((root<<1)+1, n);
          }
          else
                  r->rchild = NULL;
 
  }

root<<1,是乘2的意思。

为什么这么判断,这是因为在二叉树中若第i个节点存在,若存在左子树,与右子树,则左子树序号为2^{i},右子树的序号为2^{i}+1 

2.二叉树的遍历

2.1.前序遍历

前序遍历的顺序为根节点,左节点,右节点

  int liftr(bintree* b)
  {
          if( b == NULL)
          {
                  return 0;
          }
          //先访问根节点
          printf("%d\n", b->data);
          //再访问左节点
          liftr(b->lchild);
          //最后访问右节点
          liftr(b->rchild);
          return 0;
  }

2.2.中序遍历

中序遍历顺序为左节点,根节点,右节点。

int rigtr(bintree* b)
{
	if( b == NULL)
	{
		return 0;
	}
	//先访问左节点
	liftr(b->lchild);
	//再访问根节点
	printf("%d\n", b->data);
	//最后访问右节点
	liftr(b->rchild);
	return 0;
}

2.3.后序遍历

后序遍历顺序为左节点,右节点, 根节点

int endtr(bintree* b)
{
	if( b == NULL)
	{
		return 0;
	}
	//先访问左节点
	liftr(b->lchild);
	//再访问右节点
	liftr(b->rchild);
	//最后访问根节点
	printf("%d\n", b->data);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

月昤昽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值