按图打印树状图

版权声明:转载请注明出处 https://blog.csdn.net/nanhuaibeian/article/details/88365889

注意别忘申请节点空间,否则呵呵呵。。。。

*root = (Bitree)malloc(LEN);

编号就不用对指针的引用了

题目(一)

  1. 题目
    编程实现:要求建立一颗二叉树以二叉链表存储,输出要求的树状编号。结点结构为:
    lchiled Data Num rchiled,
    其中二叉树的num编号域为整数类型 ,data数据域为字符类型。
    要求生成二叉树中编号,从一开始进行连续编号,每个结点的编号大于其左右孩子的编号,同一个结点的左右孩子中,其左孩子的编号小于其右孩子的编号。
    请给出对二叉树中结点的实现如上要求并按如下右图树状实现编号的程序。
    测试数据:输入AB∪D∪∪CE∪F∪∪∪(其中符号∪代表空格)
    在这里插入图片描述
  2. 代码
#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(Bitnode)
//定义二叉树的二叉链表结点结构
typedef struct node {
	char data;
	int num;
	struct node *lchild;
	struct node *rchild;
} Bitnode,*Bitree;

//创建二叉树
void CreatBitree(Bitree *root) {
	char ch;
	ch = getchar();
	if(ch=='.') {	//# 代表空节点
		*root = NULL;
		return;
	} else {
		*root = (Bitree)malloc(LEN);
		(*root)->data = ch;
		CreatBitree(&((*root)->lchild));
		CreatBitree(&((*root)->rchild));
	}
}
//观察题目,发现序号结果是后序遍历次序,为创建的二叉树创建编号
int num=0;
void postorder(Bitree root) {
	if(root==NULL)	return; 
	postorder(root->rchild);
	postorder(root->lchild);
	num++;
	root->num = num;
}
//先序遍历二叉树,root为指向二叉树根节点的指针
void Preorder(Bitree root,int nlayer) {
	int i;
	if(root==NULL) return;
	Preorder(root->rchild,nlayer+1);
	for(i=0; i<nlayer; i++)
		printf(" ");
	printf("%c-%d\n",root->data,root->num);
	Preorder(root->lchild,nlayer+1);
}

int main() {
	Bitree root=NULL;
	int nlayer=1;
	printf("请输入二叉树结点:");
//	创建二叉树
	CreatBitree(&root);

//	为二叉树编号
	postorder(root);
	printf("这棵二叉树的结果图示为:\n");
//	打印二叉树
	Preorder(root,nlayer);
	return 0;
}

  1. 解题关键
    1. 一定要先审题,搞清题目的意思
    2. 动笔写写,观察观察
    3. 编号建表不能一块完成,代码尽量分块写,先建表,在编号

题目(二)

  1. 题目
    二叉排序树: ①要求建立以二叉链表方式存储的二叉排序树。
    ②按树状输出(如下图);
    ③输出结点值递减结果。
    在这里插入图片描述
    2.代码
#include "stdio.h"
#include "malloc.h"
#define LEN sizeof(bitnode)
typedef struct node {
	char ch;
	struct node *lchild;
	struct node *rchild;
}*bitree,bitnode;

void insert(bitree *root,char ch) {
	if(*root==NULL) {
		*root =(bitree)malloc(LEN);
		(*root)->ch = ch;
		(*root)->lchild = (*root)->rchild = NULL;
	} else if(ch>(*root)->ch)	insert(&((*root)->rchild),ch);
	else if(ch<(*root)->ch)	insert(&((*root)->lchild),ch);
}
void creat(bitree *root) {
	char ch;
	*root = NULL;
	ch = getchar();
	while(ch!='@') {
		insert(root,ch);
		ch = getchar();
	}
}
void print1(bitree root,int nlayer) {
	int i;
	if(root!=NULL) {
		print1(root->rchild,nlayer+1);
		for(i=0; i<nlayer; i++)
			printf(" ");
		printf("%c\n",root->ch);

		print1(root->lchild,nlayer+1);
	}
}
//递减序列,逆中序遍历
void print2(bitree root) {
	if(root!=NULL) {
		print2(root->rchild);
		printf("%c ",root->ch);
		print2(root->lchild);
	}
}
void main() {
	int nlayer =1;
	bitree root;
	creat(&root);
	print1(root,nlayer);
	print2(root);
}

猜你喜欢

转载自blog.csdn.net/nanhuaibeian/article/details/88365889
今日推荐