c++用创建结点方法创建二叉树并输出二叉树
时间: 2024-01-23 20:12:31 浏览: 90
在C++中,可以使用结构体来定义二叉树的结点,然后通过递归的方式来创建二叉树。下面是一个示例代码,可以创建二叉树并输出二叉树的前序、中序和后序遍历结果:
```
#include <iostream>
using namespace std;
// 定义二叉树结点
struct TreeNode {
char val;
TreeNode* left;
TreeNode* right;
TreeNode(char x) : val(x), left(NULL), right(NULL) {}
};
// 创建二叉树
void createTree(TreeNode* &root) {
char ch;
cin >> ch;
if (ch == '#') {
root = NULL;
} else {
root = new TreeNode(ch);
createTree(root->left);
createTree(root->right);
}
}
// 前序遍历
void preOrder(TreeNode* root) {
if (root == NULL) {
return;
}
cout << root->val << " ";
preOrder(root->left);
preOrder(root->right);
}
// 中序遍历
void inOrder(TreeNode* root) {
if (root == NULL) {
return;
}
inOrder(root->left);
cout << root->val << " ";
inOrder(root->right);
}
// 后序遍历
void postOrder(TreeNode* root) {
if (root == NULL) {
return;
}
postOrder(root->left);
postOrder(root->right);
cout << root->val << " ";
}
int main() {
TreeNode* root = NULL;
cout << "请输入前序二叉树字符:" << endl;
createTree(root);
cout << "前序遍历二叉树:";
preOrder(root);
cout << endl;
cout << "中序遍历二叉树:";
inOrder(root);
cout << endl;
cout << "后序遍历二叉树:";
postOrder(root);
cout << endl;
return 0;
}
```
阅读全文