二叉树的建立,遍历,节点个数,深度

本文介绍了一种使用C语言实现二叉树的方法,包括树的创建、先序遍历和中序遍历,以及如何计算二叉树的深度。通过递归的方式实现了二叉树节点的遍历,并采用动态规划的思想来确定树的深度。

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

#include "stdio.h"
#include "malloc.h"

typedef  struct tree_node
{
	int date;
	struct tree_node *L_child;
	struct tree_node *R_child;

}node;


void create_tree(node * &tree)
{
	int ch;
	scanf("%d", &ch);
	if(ch!=0)
	{
		tree=(node *)malloc(sizeof(node));
		tree->date=ch;
		create_tree(tree->L_child);
		create_tree(tree->R_child);
	}
	else	//这一句必须有 ,不然后期遍历树时,则无法判断子树是否为空(null)
		tree=NULL;
		
}

void qianxu_view(node *tree)
{
	if(tree)
	{
		printf("%d",tree->date );
		qianxu_view(tree->L_child);
		qianxu_view(tree->R_child);
	
	}
	
}

void zhongxu_view(node *tree)
{
	if(tree)
	{
		
		zhongxu_view(tree->L_child);
		printf("%d",tree->date);
		zhongxu_view(tree->R_child);
	
	}

}


int max(int a ,int b)
{
	if(a>b)
		return a;
	else 
		return b;

}

int tree_dep(node *tree )//二叉树的深度
{
	
	if(tree->L_child==NULL && tree->R_child==NULL)
		return 1;

	else if(tree->L_child==NULL && tree->R_child!=NULL)
		return  tree_dep(tree->R_child)+1;

	else if(tree->L_child!=NULL && tree->R_child==NULL)
		return tree_dep(tree->L_child)+1;

	else if(tree->L_child!=NULL && tree->R_child!=NULL)
		return max(tree_dep(tree->L_child),tree_dep(tree->R_child))+1;
	
}



int main()
{
	node *tree;
	//这为什么事 node*,而不是node,因为程序后面要的调用malloc来开辟空间
	//malloc原型是 extern void *malloc(unsigned int num_bytes); 
	//可以看到malloc函数返回的是(void *)类型,是一个指针类型,所以要用 node*;

	create_tree(tree);
	if(tree!=NULL)
	{
		printf("先序%d:");
		qianxu_view(tree);
		printf("中序%d:");
		zhongxu_view(tree);
		
		printf("\n\n深度--%d\n",tree_dep(tree));
	}
	

}

求深度的时候用到动态规划:

  递归方程:dep(tree))= max { dep(tree->L) , dep(tree->R)} + 1;

  边界条件:当 tree->L && tree ->L  都为NULL时,dep(tree)为1;


 树的结构为:



树的输入结构:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值