题目:
思路一:度为1的结点个数:要么左子树为空,右子树不为空;或者右子树为空,左子树不为空;采用这种思想不断地向下迭代。
代码:
#include<iostream>
using namespace std;
typedef struct BinaryTree
{
char data;
struct BinaryTree* leftchild;
struct BinaryTree* rightchild;
}BT;
void BinaryTreePreCreate(BT*& root)
{
char a;
cin >> a;
if (a == '#')
root = NULL;
else
{
root = (BT*)malloc(sizeof(BT));
root->data = a;
BinaryTreePreCreate(root->leftchild);
BinaryTreePreCreate(root->rightchild);
}
}
int Count = 0;//用全局变量记录度为1的结点个数
void BinaryTreeOneNode(BT* root)
{
if (root == NULL)
return;
if (root->leftchild == NULL)
{
if (root->rightchild != NULL)
Count++;
}
if (root->rightchild == NULL)
{
if (root->leftchild != NULL)
Count++;
}
BinaryTreeOneNode(root->leftchild);
BinaryTreeOneNode(root->rightchild);
}
int main()
{
BT* tree;
BinaryTreePreCreate(tree);
BinaryTreeOneNode(tree);
printf("%d", Count);
return 0;
}
思路二:这里的思路二是采用了二叉树的性质求解,首先需要算出结点的总个数,用总个数去减去结点为0的个数(即叶子结点个数),再减去度为2的结点个数,而根据性质我们又可以知道,度为2的结点个数又比叶子节点个数少1,所有就有X1+2X0-1=X总,(X1表示度为0结点个数,X0表示叶子结点个数,X总表示结点总个数),通过这样的方法也可以完成,不过比较繁琐,就不提倡这种方法,不过可以掌握这种数学的思想。