用递归方法求二叉树(二叉链表结构)双分支节点的个数

用递归方法求二叉树(二叉链表结构)双分支节点的个数,第1张

求解的方法

int DsonNodes(BiTree T){
	if(T == NULL) return 0;
	if(T->lchild && T->rchild){
		return DsonNodes(T->lchild) + DsonNodes(T->rchild) + 1;
	}
	return DsonNodes(T->lchild) + DsonNodes(T->rchild);
}

此方法运行的环境

#include 
#include
#include
#define maxsize 100
//二叉树的创建序列 
//ab#df###c#e##
//abd##e##cf###
typedef struct BiNode{
	char date;
	struct BiNode *lchild,*rchild;
}BiNode,*BiTree;

BiNode* CreateBiTree();
void Traverse(BiNode *p);

int DsonNodes(BiTree T); 
int main(){
	BiTree t = CreateBiTree();
	printf("双分支节点的个数:%d",DsonNodes(t));
	return 0;
}

//用递归方法以中序遍历的方式创建二叉树 
BiNode* CreateBiTree(){
	BiNode *p;
	char a;
	scanf("%c",&a);
	if(a=='#')
	p=NULL;
	else{
		p=(BiNode *)malloc(sizeof(BiNode));
		p->date=a;
		p->lchild=CreateBiTree();
		p->rchild=CreateBiTree();
	}	
	return p;
}
//递归方法中序遍历二叉树 
void Traverse(BiNode *p){
	if(p==NULL){
		return;
	}
	else{
		Traverse(p->lchild);
		printf("%c",p->date);
		Traverse(p->rchild);
	}
	return;
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/798980.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-06
下一篇2022-05-06

发表评论

登录后才能评论

评论列表(0条)

    保存