浅析递归树

#include<stdio.h>
#include<stdlib.h>
//#include<string.h>

typedef struct SNode
{
	char x;
	SNode *Lchild;
	SNode *Rchild;

}BiTNode,* BiTree;

BiTree creatBiTree()	//有返回值的创建树  调用一级指针
{
	BiTree root;
	char ch;
	ch=getchar();
	if(ch=='#')
		root=NULL;
	else
	{
		root=(BiTree)malloc(sizeof(BiTNode));
		root->x=ch;
		root->Lchild=creatBiTree();
		root->Rchild=creatBiTree();
	}
	return root;

}

void creatBiTree(BiTree *root)   //(引用二级指针 无返回值 传递的为*root的地址   相当于在这个函数中root存的
{								 //是传来root的地址  而*root则为传来的root)
	char ch;
	ch=getchar();
	if(ch=='#')
		(*root)=NULL;
	else
	{
		*root=(BiTree)malloc(sizeof(BiTNode));
		(*root)->x=ch;
		creatBiTree(&((*root)->Lchild));
		creatBiTree(&((*root)->Rchild));
	}
}

void PreOrder(BiTree root)    //先序遍历
{
	if(root)
	{
		printf("%5c",root->x);
		PreOrder(root->Lchild);
		PreOrder(root->Rchild);
	}
}

void Inorder(BiTree root)    //中序遍历
{
	if(root)
	{
		Inorder(root->Lchild);
		printf("%5c",root->x);
		Inorder(root->Rchild);
	}
}

void PostOrder(BiTree root)   //后续遍历
{
	if(root)
	{
		PostOrder(root->Lchild);
		PostOrder(root->Rchild);
		printf("%4c",root->x);
	}
}

int count=0;                           //先序遍历统计二叉树中的节点数
void Orderjiedian(BiTree root)
{
	if(root)
	{
		count++;
		Orderjiedian(root->Lchild);
		Orderjiedian(root->Rchild);

	}
}

void printyezi(BiTree root)          //遍历输出二叉树叶子节点(相比遍历只多了个判断没有左右节点时输出)
{
	if(root)
	{
		printyezi(root->Lchild);
		if(root->Lchild==NULL&&root->Rchild==NULL)
			printf("%4c",root->x);
		printyezi(root->Rchild);
	}
}

int leaf(BiTree root)     //后序遍历统计叶子节点数目(必须为后续)
{
	int nl,nr;
	if(root==NULL)
		return 0;
	if((root->Lchild==NULL)&&(root->Rchild==NULL))
		return 1;
	nl=leaf(root->Lchild);
	nr=leaf(root->Rchild);
	return (nl+nr);
}


int PostTreeDepth(BiTree root)  //求二叉树的高度  递归有返回值调用
{
	int hl,hr,h;
	if(root==NULL)
		return 0;
	else
	{
		hl=PostTreeDepth(root->Lchild);
		hr=PostTreeDepth(root->Rchild);
		h=(hl>hr? hl:hr)+1;
		return h;
	}
}

int main(void)
{
	BiTree root;
//	creatBiTree(&root);
	root=creatBiTree();
	printf("\n");
	printf("%d",PostTreeDepth( root));
//	printf("%d",count);
	printf("\n");
	return 0;

}
总结:
树中递归无返回值  其实就相当于先把函数中的左或者右先遍历完  找到最后一层  从最后一层开始 逐个往上走  直到这个节点的左右叶子遍历完
再进入它的上一个节点    只有当一个节点他的子叶遍历完 才会进入它上一个节点

树中递归有返回值  其实也就相当于从最后一个节点开始逐一返回    叶子节点的左右孩子相加作为上一个双亲节点的子叶

创建树时不能用一级指针的传递  因为开辟空间是在调用函数中的  在函数结束时释放开辟的空间 所以等于无操作


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值