



#include <iostream>
#include <queue>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
// 创建二叉树
TreeNode* createBinaryTree() {
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
return root;
}
// 前序遍历
void preorder(TreeNode* root) {
if (root == nullptr) return;
cout << root->val << " ";
preorder(root->left);
preorder(root->right);
}
// 中序遍历
void inorder(TreeNode* root) {
if (root == nullptr) return;
inorder(root->left);
cout << root->val << " ";
inorder(root->right);
}
// 后序遍历
void postorder(TreeNode* root) {
if (root == nullptr) return;
postorder(root->left);
postorder(root->right);
cout << root->val << " ";
}
// 层次遍历
void levelOrder(TreeNode* root) {
if (root == nullptr) return;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* current = q.front();
q.pop();
cout << current->val << " ";
if (current->left != nullptr) q.push(current->left);
if (current->right != nullptr) q.push(current->right);
}
}
// 计算树高
int height(TreeNode* root) {
if (root == nullptr) return 0;
return max(height(root->left), height(root->right)) + 1;
}
// 计算节点数
int countNodes(TreeNode* root) {
if (root == nullptr) return 0;
return 1 + countNodes(root->left) + countNodes(root->right);
}
int main() {
TreeNode* root = createBinaryTree();
cout << "前序遍历: ";
preorder(root);
cout << endl;
cout << "中序遍历: ";
inorder(root);
cout << endl;
cout << "后序遍历: ";
postorder(root);
cout << endl;
cout << "层次遍历: ";
levelOrder(root);
cout << endl;
cout << "树高: " << height(root) << endl;
cout << "节点数: " << countNodes(root) << endl;
return 0;
}