用c++以二叉链表作为二叉树的存储结构,计算二叉树的高度和最大的宽度
时间: 2023-11-29 16:23:38 浏览: 97
二叉链表结构的二叉树的类定义-树和森林--清华大学课程讲义-数据结构(PPT)
好的,我知道了,下面是代码实现:
```cpp
#include <iostream>
#include <queue>
using namespace std;
// 二叉树结点
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 二叉树类
class BinaryTree {
public:
// 构造函数
BinaryTree() : root(NULL) {}
// 插入结点
void insert(int val) {
TreeNode* node = new TreeNode(val);
if (root == NULL) {
root = node;
return;
}
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* cur = q.front();
q.pop();
if (cur->left == NULL) {
cur->left = node;
return;
} else {
q.push(cur->left);
}
if (cur->right == NULL) {
cur->right = node;
return;
} else {
q.push(cur->right);
}
}
}
// 计算二叉树的高度
int getHeight() {
return getHeight(root);
}
// 计算二叉树的最大宽度
int getMaxWidth() {
if (root == NULL) {
return 0;
}
int maxWidth = 1;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int size = q.size();
maxWidth = max(maxWidth, size);
for (int i = 0; i < size; i++) {
TreeNode* cur = q.front();
q.pop();
if (cur->left != NULL) {
q.push(cur->left);
}
if (cur->right != NULL) {
q.push(cur->right);
}
}
}
return maxWidth;
}
private:
TreeNode* root;
// 辅助函数:计算以root为根的二叉树的高度
int getHeight(TreeNode* root) {
if (root == NULL) {
return 0;
}
int leftHeight = getHeight(root->left);
int rightHeight = getHeight(root->right);
return max(leftHeight, rightHeight) + 1;
}
};
int main() {
BinaryTree tree;
tree.insert(1);
tree.insert(2);
tree.insert(3);
tree.insert(4);
tree.insert(5);
tree.insert(6);
tree.insert(7);
cout << "Height of the binary tree is " << tree.getHeight() << endl;
cout << "Max width of the binary tree is " << tree.getMaxWidth() << endl;
return 0;
}
```
输出结果为:
```
Height of the binary tree is 3
Max width of the binary tree is 4
```
其中,getHeight()函数使用递归计算二叉树的高度;getMaxWidth()函数使用队列实现宽度优先搜索,计算二叉树的最大宽度。
阅读全文