二叉树算法

该博客主要展示了二叉树的创建与遍历算法的代码实现。通过定义二叉树节点结构,实现了前序、中序和后序遍历函数,还编写了创建二叉树的函数,利用递归方式根据用户输入构建二叉树。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define ElementType int

//node structure constructor
typedef struct bt {
   ElementType data;
   struct bt *lchild, *rchild;
} BinaryTreeNode,*BTRoot;

//function declear
InOrder(BTRoot root);
PreOrder(BTRoot root);
PostOrder(BTRoot root);

//the main function to excute
main()
{
  BTRoot r=malloc(sizeof(BinaryTreeNode));
  CreateTree(r,1);
  printf("/nPreorder :");
  PreOrder(r);
  printf("/nInorder :");
  InOrder(r);
  printf("/nPostorder:");
  PostOrder(r);
  while(1) ;
  return 0;
}

//inorder function
InOrder(BTRoot root)
{
  if(!root) return 0;
  InOrder(root->lchild);
  printf("%4d",root->data);
  InOrder(root->rchild);
}

//preorder function
PreOrder(BTRoot root)
{
  if(!root) return 0;
  printf("%4d",root->data);
  PreOrder(root->lchild);
  PreOrder(root->rchild);
}

//postorder function
PostOrder(BTRoot root)
{
  if(!root) return 0;
  PostOrder(root->lchild);
  PostOrder(root->rchild);
  printf("%4d",root->data);
}
 /*receive the input data and create a node each time!*/
CreateTree(BTRoot root,int NodeNum) /* Preorder */
{
  ElementType x;
  int i,layer;

  layer=log(NodeNum)/log(2)+1;
  printf("/nInput data for Node %d in layer %d :",NodeNum,layer);
  scanf("%d",&x);
  root->data=x;

  printf("create lchild for Node %d in layer %d (0 for No)?",NodeNum,layer);
  scanf("%d",&i);
  if(i==0) root->lchild=NULL;
   else
    {root->lchild=(BTRoot)malloc(sizeof(BinaryTreeNode));
     CreateTree(root->lchild,2*NodeNum);
    }

  printf("create rchild for Node %d in layer %d (0 for No)?",NodeNum,layer);
  scanf("%d",&i);
  if(i==0) root->rchild=NULL;
   else
    {root->rchild=(BTRoot)malloc(sizeof(BinaryTreeNode));
     CreateTree(root->rchild,2*NodeNum+1);
    }
  return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值