1-1 统计度为1的结点数
分数 3
作者 黄龙军
单位 绍兴文理学院
要求实现函数,统计并返回二叉树中的度为1的结点数。二叉树采用二叉链表存储,结点结构如下:
1 2 3 4
| struct BiTNode { char data; BiTNode *lchild, *rchild; };
|
函数接口定义:
1
| int CountSingle(BiTNode *T);
|
其中参数 T是指向二叉树根结点的指针。
裁判测试程序样例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| #include<iostream> #include<string> using namespace std;
struct BiTNode { char data; BiTNode *lchild, *rchild; };
int CountSingle(BiTNode *T); BiTNode *CreateBiTree(string &s);
int main() { string s; while(cin>>s) { BiTNode* root=CreateBiTree(s); cout<<CountSingle(root)<<endl; } return 0; }
BiTNode *CreateBiTree(string &s) { if(s[0]=='*') { s=s.substr(1); return NULL; } BiTNode *p=new BiTNode; p->data=s[0]; s=s.substr(1); p->lchild=CreateBiTree(s); p->rchild=CreateBiTree(s); return p; }
|
输入样例:
1 2
| HDA**C*B**GF*E*** -+a**xb**-c**d**/e**f**
|
输出样例:
答案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| int CountSingle(BiTNode *T) { if (T == NULL) { return 0; } if (T->lchild == NULL && T->rchild == NULL) { return 0; } if ((T->lchild != NULL && T->rchild == NULL) || (T->lchild == NULL && T->rchild != NULL)) { return 1 + CountSingle(T->lchild) + CountSingle(T->rchild); } if (T->rchild != NULL && T->lchild != NULL) { return 0 + CountSingle(T->lchild) + CountSingle(T->rchild); } }
|
- 空树情况:若树为空(
T == NULL),度为 1 的节点数为 0。
- 叶子节点:若节点的左、右子树都为空(
T->lchild == NULL && T->rchild == NULL),度为 0,不计数。
- 度为 1 的节点:若节点的左、右子树中恰好有一个不为空(
(T->lchild != NULL && T->rchild == NULL) || (T->lchild == NULL && T->rchild != NULL)),则计数 1,并递归统计其非空子树的度为 1 节点数。
- 度为 2 的节点:若节点的左、右子树都不为空,不计数,但需递归统计左、右子树的度为 1 节点数。