ZBLOG

template BTNode* BinaryTree::buildTree(std::string& str, int& index) { if (index >= str.size()) { return nullptr; // 边界条件:已经遍历完序列 } char ch = str[index]; index++; // 移动到下一个字符 if (ch == '#') { return n...

以下是实现计算二叉树的最大宽度和求二叉树节点数目的示例代码:

template <class DataType>
int BinaryTree<DataType>::maxWidth(BTNode<DataType>* node) {
    if (node == nullptr) {
        return 0;
    }

    int maxWidth = 0;
    queue<BTNode<DataType>*> q;
    q.push(node);

    while (!q.empty()) {
        int levelSize = q.size(); // 当前层的节点个数

        maxWidth = max(maxWidth, levelSize); // 更新最大宽度

        for (int i = 0; i < levelSize; i++) {
            BTNode<DataType>* currNode = q.front();
            q.pop();

            if (currNode->lChild != nullptr) {
                q.push(currNode->lChild);
            }
            
            if (currNode->rChild != nullptr) {
                q.push(currNode->rChild);
            }
        }
    }

    return maxWidth;
}

template <class DataType>
int BinaryTree<DataType>::countNodes(BTNode<DataType>* node) {
    if (node == nullptr) {
        return 0;
    }

    int leftCount = countNodes(node->lChild);
    int rightCount = countNodes(node->rChild);

    return leftCount + rightCount + 1; // 加上当前节点本身
}

使用方式:

BinaryTree<char> binaryTree;
binaryTree.CreateBinaryTree();

// 计算二叉树的最大宽度
int maxWidth = binaryTree.maxWidth(binaryTree.getRoot());

// 求二叉树的节点数目
int nodeCount = binaryTree.countNodes(binaryTree.getRoot());

请注意,上述代码是根据给定的二叉树结构进行的示例实现,您可能需要根据自己的实际情况进行适当修改。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=8837

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?