设计算法求出二叉树中度为2与度为1的结点个数的差值

【问题描述】使用先序方式构建二叉树,求度为2与度为1的结点个数之差。

【输入形式】按先序遍历输入二叉树的结点信息,结点名称为正整数,0表示空。

【输出形式】输出度为2与度为1的节点个数的差值(可以为负)

【样例输入】1 2 4 0 0 5 0 6 0 0 3 0 7 8 0 0 9 0 0

【样例输出】1

#include<iostream>
#include<stdio.h>
#include<queue>
#include<malloc.h>
#include<stdlib.h>
using namespace std;
typedef int elem;
typedef struct Tnode {
	elem data;
	struct Tnode* left;
	struct Tnode* right;
}Tnode,*Ptree;
void init(Ptree& T) {//建立二叉树
	elem a;
	cin >> a;
	if (a == 0)
		T = NULL;
	else {
		T = (Ptree)malloc(sizeof(Tnode));
		if (T == NULL)
			return;
		else {
			T->data = a;
			T->left = NULL;
			T->right = NULL;
			init(T->left);
			init(T->right);
		}
	}
}
void calulate(Ptree T, int& two, int& one) {//计算度为2和1
	if (!T)return;
	if (T->right != NULL && T->left != NULL)
		two++;
	else if (T->left != NULL || T->right != NULL)
		one++;
	calulate(T->left, two, one);
	calulate(T->right, two, one);

}
int main() {
	Ptree T = NULL;
	init(T);
	int two = 0, one = 0;
	calulate(T, two, one);
	cout << two-one;
	//system("pause");
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值