写的二叉排序树,前序、中序、后序序列完全一样,不知道哪里出了问题

冷眼观world 2020-06-21 02:18:49
这里采用将数据先全部输入数组,再从数组中将数据插入树
#include <iostream>
#include <cstdlib>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
struct node
{
int val;
node* left;
node* right;
node(int v) : val(v), left(NULL), right(NULL) {}
};
vector<int> vec; //数组
void search(node*, int, int);
void insert(node* &, int);
void preorder(node* root);
void inorder(node* root);
void postorder(node* root);
void levelorder(node* root);
node* creat_tree();
int main()
{
int value;
while (cin >> value)
vec.push_back(value);
node* root = creat_tree();
cout << "先序序列:";
preorder(root);
cout << endl;
cout << "中序序列:";
inorder(root);
cout << endl;
cout << "后序序列:";
postorder(root);
cout << endl;
system("pause");
return 0;
}
node* creat_tree() //建立树
{
node* root = NULL;
for (int i = 0;i < vec.size(); i++)
insert(root, vec[i]);
return root;
}
void search(node* root, int x) //寻找结点
{
if (!root)
return;
if (root -> val == x)
cout << "find it!";
else if (x < root -> val)
search(root -> left, x);
else
search(root -> right, x);
}
void insert(node* &root, int x) //插入结点
{
if (!root)
{
root = new node(x); //因为传入的参数采用了引用,所以这里直接赋值就能实现插入
return;
}
if (root -> val == x)
return;
else if (x < root -> val) //二叉排序树,小于则在左边
insert(root -> left, x);
else
insert(root -> right, x);
}
void preorder(node* root) //前序遍历
{
if (root == NULL)
return;
cout << root -> val;
preorder(root -> left);
preorder(root -> right);
}
void inorder(node* root) //中序
{
if (root == NULL)
return;
inorder(root -> left);
cout << root -> val;
inorder(root -> right);
}
void postorder(node* root) //后序
{
if (root == NULL)
return;
postorder(root -> left);
postorder(root -> right);
cout << root -> val;
}
void levelorder(node* root) //层序遍历
{
queue<node*> que;
que.push(root);
while (!que.empty())
{
node* p = que.front();
cout << p -> val;
que.pop();
if (p -> left != NULL)
que.push(p -> left);
if (p -> right != NULL)
que.push(p -> right);
}
}

但是三个序列完全一样
...全文
173 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
冷眼观world 2020-06-21
  • 打赏
  • 举报
回复
引用 1 楼 真相重于对错 的回复:
cin>>value 你的输入是一个数
啊这,是我傻了,谢谢
真相重于对错 2020-06-21
  • 打赏
  • 举报
回复
cin>>value 你的输入是一个数

64,641

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧