创建二叉树和实现二叉树的三种遍历 a. 根据提示输入字符型数据创建二叉树,输入值为所有字符型数据 b. 输出为遍历后的每个结点的值的顺序 c. 创建二叉树并能实现二叉树的先序、中序、后序遍历 d. 如果输入数据为:a b c 输出结果为:a b c b a c b c a 程序流程:main()àclrscr()àcreatetree()àpreorder()àinorder()àpostorder
时间: 2023-11-27 11:53:34 浏览: 58
以下是 C++ 代码实现:
```cpp
#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 c;
cin >> c;
if(c == '#'){
root = NULL;
}
else{
root = new TreeNode(c);
createTree(root->left);
createTree(root->right);
}
}
void preorder(TreeNode* root){
if(root){
cout << root->val << " ";
preorder(root->left);
preorder(root->right);
}
}
void inorder(TreeNode* root){
if(root){
inorder(root->left);
cout << root->val << " ";
inorder(root->right);
}
}
void postorder(TreeNode* root){
if(root){
postorder(root->left);
postorder(root->right);
cout << root->val << " ";
}
}
int main(){
cout << "Please input the characters to create a binary tree: " << endl;
TreeNode* root;
createTree(root);
cout << "Preorder traversal result: ";
preorder(root);
cout << endl;
cout << "Inorder traversal result: ";
inorder(root);
cout << endl;
cout << "Postorder traversal result: ";
postorder(root);
cout << endl;
return 0;
}
```
测试输入数据为 "a b # # c # #",输出结果为:
```
Preorder traversal result: a b c
Inorder traversal result: b a c
Postorder traversal result: b c a
```
阅读全文