用二叉链表表示树,结点的值为结点的序号,创建n个结点的完全二叉树,输出前、中、后三种遍历。
时间: 2024-05-01 16:20:53 浏览: 91
以下是用C++代码实现:
```cpp
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
void createBinaryTree(TreeNode* &root, int num, int n) {
if (num <= n) {
root = new TreeNode(num);
createBinaryTree(root->left, num * 2, n);
createBinaryTree(root->right, num * 2 + 1, n);
}
}
void preOrder(TreeNode* root) {
if (root != nullptr) {
cout << root->val << " ";
preOrder(root->left);
preOrder(root->right);
}
}
void inOrder(TreeNode* root) {
if (root != nullptr) {
inOrder(root->left);
cout << root->val << " ";
inOrder(root->right);
}
}
void postOrder(TreeNode* root) {
if (root != nullptr) {
postOrder(root->left);
postOrder(root->right);
cout << root->val << " ";
}
}
int main() {
int n;
cout << "请输入结点个数n:";
cin >> n;
TreeNode* root = nullptr;
createBinaryTree(root, 1, n);
cout << "前序遍历结果:";
preOrder(root);
cout << endl;
cout << "中序遍历结果:";
inOrder(root);
cout << endl;
cout << "后序遍历结果:";
postOrder(root);
cout << endl;
return 0;
}
```
其中,`createBinaryTree`函数用于创建完全二叉树,`preOrder`、`inOrder`、`postOrder`函数分别用于前序、中序、后序遍历。
阅读全文