以下是使用 C++ 实现计算二叉树宽度的代码,不使用 C++11 特性: ```cpp #include <iostream> template<typename T> struct BintreeNode { T data; BintreeNode* left; BintreeNode* right; BintreeNode(T value) : data(value), left(NULL), right(NULL) {} }; template<typename T> class BinaryTree { public: void levelNum(BintreeNode<T>* root, int a[], int h) { if (root == NULL) { return; } a[h]++; levelNum(root->left, a, h + 1); levelNum(root->right, a, h + 1); } int getWidth(BintreeNode<T>* root) { int a[100] = {0}; levelNum(root, a, 0); int maxWidth = 0; for (int i = 0; i < 100; i++) { if (a[i] > maxWidth) { maxWidth = a[i]; } } return maxWidth; } }; // 构建二叉树的函数 template<typename T> BintreeNode<T>* buildTree(const std::string& str, int& index) { if (index >= str.size()) { return NULL; } if (str[index] == '#') { index++; return NULL; } BintreeNode<T>* root = new BintreeNode<T>(str[index]); index++; root->left = buildTree(str, index); root->right = buildTree(str, index); return root; } int main() { std::string input = "abc##de#g##f"; int index = 0; BinaryTree<char> tree; BintreeNode<char>* root = buildTree(input, index); int width = tree.getWidth(root); std::cout << width << std::endl; return 0; } ``` [2024-11-10 23:41:27 | AI写代码神器 | 497点数解答]