帮我写一个C++程序,要求二叉树的建立,遍历,求高度,求叶子结点,度为二的结点,度为一的结点个数等基本操作的实现
时间: 2024-12-24 20:23:42 浏览: 3
在C++中,我们可以创建一个简单的二叉树结构,并实现插入节点、遍历(前序、中序、后序)、求高度、计算叶子节点、度为二的节点以及度为一的节点个数等功能。下面是一个基础的二叉树模板和相关操作的实现:
```cpp
#include <iostream>
using namespace std;
// 定义二叉树的节点
template <typename T>
struct TreeNode {
T val;
TreeNode* left;
TreeNode* right;
TreeNode(T x) : val(x), left(nullptr), right(nullptr) {}
};
// 插入节点到二叉树
template <typename T>
TreeNode<T>* insert(TreeNode<T>* root, T val) {
if (root == nullptr)
return new TreeNode<T>(val);
else if (val < root->val)
root->left = insert(root->left, val);
else
root->right = insert(root->right, val);
return root;
}
// 前序遍历
template <typename T>
void preorderTraversal(TreeNode<T>* root, vector<T>& result) {
if (root != nullptr) {
result.push_back(root->val);
preorderTraversal(root->left, result);
preorderTraversal(root->right, result);
}
}
// 中序遍历
template <typename T>
void inorderTraversal(TreeNode<T>* root, vector<T>& result) {
if (root != nullptr) {
inorderTraversal(root->left, result);
result.push_back(root->val);
inorderTraversal(root->right, result);
}
}
// 后序遍历
template <typename T>
void postorderTraversal(TreeNode<T>* root, vector<T>& result) {
if (root != nullptr) {
postorderTraversal(root->left, result);
postorderTraversal(root->right, result);
result.push_back(root->val);
}
}
// 求树的高度
template <typename T>
int height(TreeNode<T>* root) {
if (root == nullptr)
return 0;
int leftHeight = height(root->left);
int rightHeight = height(root->right);
return max(leftHeight, rightHeight) + 1;
}
// 计算叶子节点
template <typename T>
int countLeaves(TreeNode<T>* root) {
if (root == nullptr || (root->left == nullptr && root->right == nullptr))
return 1;
else
return countLeaves(root->left) + countLeaves(root->right);
}
// 计算度为二的节点
template <typename T>
int countDegreeTwo(TreeNode<T>* root) {
int degreeTwo = 0;
if (root != nullptr) {
if (root->left != nullptr && root->right != nullptr)
degreeTwo++;
degreeTwo += countDegreeTwo(root->left);
degreeTwo += countDegreeTwo(root->right);
}
return degreeTwo;
}
// 计算度为一的节点
template <typename T>
int countDegreeOne(TreeNode<T>* root) {
int degreeOne = 0;
if (root != nullptr) {
if (root->left != nullptr)
degreeOne++;
if (root->right != nullptr)
degreeOne++;
}
return degreeOne;
}
int main() {
// 创建并插入节点示例
TreeNode<int> *root = nullptr;
root = insert(root, 5);
insert(root, 3);
insert(root, 7);
insert(root, 2);
insert(root, 4);
insert(root, 6);
insert(root, 8);
// 使用遍历函数打印结果
vector<int> result;
cout << "Preorder traversal: ";
preorderTraversal(root, result);
cout << "\nInorder traversal: ";
inorderTraversal(root, result);
cout << "\nPostorder traversal: ";
postorderTraversal(root, result);
// 计算高度、叶子节点、度为二的节点、度为一的节点
cout << "\nHeight: " << height(root) << endl;
cout << "Leaf nodes: " << countLeaves(root) << endl;
cout << "Nodes of degree 2: " << countDegreeTwo(root) << endl;
cout << "Nodes of degree 1: " << countDegreeOne(root) << endl;
return 0;
}
```
阅读全文