首页 > 试题广场 >

设一棵二叉树以二叉链表表示,试以成员函数形式编写有关二叉树的

[问答题]

设一棵二叉树以二叉链表表示,试以成员函数形式编写有关二叉树的递归算法。

1 )统计二叉树中度为 1 的结点个数;

2 )统计二叉树中度为 2 的结点个数。

(提示:递归算法如 32 题所示)


解答:( 1 )统计二叉树中度为 1 的结点个数。

Template<class Type>

Int BinaryTree<Type> ::Degree1(BinTreeNode<Type> *t)const{

If(t==NULL) return 0;

If(t->leftchild!=NULL &&t->rightchild==NULL || t->leftchild==NULL &&t->rightchild!=NULL)

Return 1+Degree1(t->leftchild)+Degree1(t->rightchild);

Return Degree1(t->leftchild)+Degree1(t->rightchild);

}

(2) 统计二叉树中度为 2 的结点个数。

Template<class Type>

Int BinaryTree<Type> ::Degree2(BinTreeNode<Type> *t)const{

If(t==NULL) return 0;

If(t->leftchild!=NULL &&t->rightchild!=NULL )

Return 1+Degree2(t->leftchild)+Degree2(t->rightchild);

Return Degree2(t->leftchild)+Degree2(t->rightchild);

}

发表于 2017-09-21 14:37:24 回复(0)