【问题描述】使用先序方式构建二叉树,求度为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;
}