C语言 数据结构 帮忙设计一个简单的程序 计算结点个数
来源:学生作业帮 编辑:神马作文网作业帮 分类:综合作业 时间:2024/09/20 14:35:49
C语言 数据结构 帮忙设计一个简单的程序 计算结点个数
“程序中分别有左右子树结点的个数”这句话表示没说清楚.
我们数据结构刚好上机也有这道题,不过我用的是c++11,领会精神就行,不用太在意语法.struct BitNode{
ElemType data;
BitNode *lchild,*rchild;
};
template<typename ElemType>
size_t BinaryTree<ElemType>::totalLeaves(){
size_t sum = 0;
_postorderTraversal([&sum](TBitNode **val){
sum += ((*val)->lchild == nullptr) && ((*val)->rchild == nullptr);
});
return sum;
}
template<typename ElemType>
void BinaryTree<ElemType>::_postorderTraversal(function<void(BitNode<ElemType>**)> visit){
_postorderRecursive(&root, visit);
root = nullptr;
}
template<typename ElemType>
void BinaryTree<ElemType>::_postorderRecursive(BitNode<ElemType> **node, function<void (BitNode<ElemType>**)> visit){
if(node && *node){
_postorderRecursive(&((*node)->lchild),visit);
_postorderRecursive(&((*node)->rchild),visit);
visit(node);
}
}如果需要,我可以把整个工程发给你
我们数据结构刚好上机也有这道题,不过我用的是c++11,领会精神就行,不用太在意语法.struct BitNode{
ElemType data;
BitNode *lchild,*rchild;
};
template<typename ElemType>
size_t BinaryTree<ElemType>::totalLeaves(){
size_t sum = 0;
_postorderTraversal([&sum](TBitNode **val){
sum += ((*val)->lchild == nullptr) && ((*val)->rchild == nullptr);
});
return sum;
}
template<typename ElemType>
void BinaryTree<ElemType>::_postorderTraversal(function<void(BitNode<ElemType>**)> visit){
_postorderRecursive(&root, visit);
root = nullptr;
}
template<typename ElemType>
void BinaryTree<ElemType>::_postorderRecursive(BitNode<ElemType> **node, function<void (BitNode<ElemType>**)> visit){
if(node && *node){
_postorderRecursive(&((*node)->lchild),visit);
_postorderRecursive(&((*node)->rchild),visit);
visit(node);
}
}如果需要,我可以把整个工程发给你