二叉树的遍历与深度和节点数的计算代码实现

二叉树有前序(中左右)中序(左中右)后序(左右中)三种方式。


可用递归的思路加上链表实现二叉树的创建与遍历。

#include<iostream>
#include<malloc.h>
using namespace std;
typedef struct node{
	char data;
	struct node*left;
	struct node*right;
}Node,*jnode;

jnode creat(jnode &t)//创建二叉树; 
{
	char a;
	cin>>a;
	if(a=='#')
	{
		t=NULL;
	}
	else
	{
		t=(jnode)malloc(sizeof(node));
		t->data=a;
		t->left=creat(t->left);
		t->right=creat(t->right);
	}
	return t;//????? 
}
void qianxu(jnode &t)//前序遍历二叉树; 
{
	if(t)
	{
		cout<<t->data;
		qianxu(t->left);
		qianxu(t->right); 
	}
}
void zhongxu(jnode &t)//中序遍历二叉树; 
{
   if(t)
   {
      zhongxu(t->left);
	  cout<<t->data;
	  zhongxu(t->right);	
   }	
} 
void houxu(jnode &t)
{
	if(t)
	{
		houxu(t->left);
		houxu(t->right);
		cout<<t->data;
	}
 } 
 int shendu(jnode &t)//找出二叉树的深度; 
 {
 	int sum=0,depthl,depthr;
    if(t==NULL)
	{
	  return 0;	
	}	
	else
	{
		depthl=shendu(t->left);
		depthr=shendu(t->right);
		sum=1+(depthl>depthr?depthl:depthr);
	}
	return sum;
 }
 int jiedian(jnode &t)//计算二叉树的节点数; 
 {
    int sum=0,m,n;
	if(t)
	{
	  if(!t->left&&!t->right)
	  {
	     sum++;	
	  }	
	  else
	  {
	  	m=jiedian(t->left);
	  	sum+=m;
	  	n=jiedian(t->right);
	  	sum+=n;
	  }
	}
	return sum;	
 } 
int main()
{
	cout<<"请输入二叉树:\n"; 
	jnode t;
	t=creat(t);
	cout<<"输出前序遍历结果\n";
	qianxu(t);
	cout<<endl;
	cout<<"输出中序遍历结果\n";
	zhongxu(t);
	cout<<endl;
	cout<<"输出后序遍历结果\n"; 
	houxu(t);
	cout<<endl;
	int m=shendu(t);
	cout<<"输出二叉树的深度\n";
	cout<<m<<endl;
	cout<<"输出二叉树的节点数\n";
	int l=jiedian(t);
	cout<<l<<endl;
	return 0;
}


普通的二叉树,节点只需包含三个域,即储存元素的data,储存左右指针的指向节点的指针lchild,rchild。

创建二叉树时同样用到递归,思路是将一棵不完整的二叉树补充完整,空缺的左孩子或有孩子用#做标记,同时令此时的左孩子或有孩子的父节点的左指针或有指针为NULL。即找到了每一次递归结束的标志。

前中后序遍历时的递归,每一次递归转向上一次递归的条件即其左右指针都为空。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值