简单先序建树

构思:

1.建立跟节点,装载输入的字符

2.根据输入的字符'#'判断是否存在做孩子

是,重复1

否,返回

3.判断是否存在右孩子

是,重复1,

否,返回

这里用到了递归思想。

遍历树可以跟建树的顺序一样,但也可以用不同的方法遍历,例如中序。

 

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

#define maxsize 30

 

typedef struct node //节点结构体

{

char c;

struct node *lchild, *rchild;

}nod, *nodlk;

 

void build_tree(nodlk *root){ //使用二级指针是为了不用返回传进的指针,使用一级指针则要返回指针给主函数,否则在主函数无法使用此树

*root = (nodlk)malloc(sizeof(nod));

char c;

scanf("%c",&c);

 

if (c == '#'){ //用#表示孩子为空

(*root)->lchild = NULL;

(*root)->rchild = NULL;

return ;

}

else 

{

(*root)->c = c;

build_tree(&((*root)->lchild));

build_tree(&((*root)->rchild));

}

return;

}

void show(nodlk root){  //打印该树

if(root != NULL){

printf("%c",root->c);

show(root->lchild);

show(root->rchild);

}

return ;

}

 

int main(void)

{

nodlk root;

printf("you can build a tree like: ");

build_tree(&root);

printf("-------------------------/n");

printf("your tree had build success: ");

show(root);

printf("/n");

return 0;

}

注:此处用的malloc如果没有使用destroy销毁,则空间不会自动销毁,除非关机。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值