自定义实现树,用先序遍历序列生成树,并求度为2的结点个数。
#includeusing namespace std; typedef char datatype; struct node { datatype data; node *lchild; node *rchild; }; typedef node *BTREE; void CreateBT(BTREE &BT) { char ch; cin >> ch; if (ch == '#') BT = NULL; else { BT = new node; BT->data = ch; CreateBT(BT->lchild); CreateBT(BT->rchild); } } int Twonodes(BTREE BT) { if (BT == NULL) return 0; else if (BT->lchild != NULL && BT->rchild != NULL) return Twonodes(BT->lchild) + Twonodes(BT->rchild) + 1; else return Twonodes(BT->lchild) + Twonodes(BT->rchild); } int main() { BTREE BT; int a; cout << "请输入树的先序遍历以构建树:"; CreateBT(BT); a = Twonodes(BT); cout << "度为2的结点个数:" << endl << a ; return 0; } // ABDH##I##EJ###CF##G##
主要参考: 《数据结构与算法》(第五版)张岩
《数据结构考研复习指导》(王道)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)