/*
这是一道模板题主要考查两个知识点:
1.构建二叉搜索树
2.由于二叉搜索树的性质 :先序遍历为最小序列
*/
#include <bits/stdc++.h>
using namespace std;
int n;
int in_[100002];
int cot = 0;
struct node {
int value;
node* l, * r;
node(int value = 0, node* l = NULL, node* r = NULL) :value(value), l(l),r(r){}
};
void insert(node * &root,int value) {
if (root == NULL) {
root = new node(value);
return;
}
else {
if (root->value > value)
insert(root->l, value);
else if (root->value < value)
insert(root->r, value);
}
}
void in(node* root) {
if (root != NULL) {
in_[cot++] = root->value;
in(root->l);
in(root->r);
}
}
int main()
{
while (cin >> n) {
//作为当前遍历的根节点
node * root=NULL;
cot = 0;
for (int i = 0; i < n; i++) {
int value;
cin >> value;
insert(root, value);
}
in(root);
for (int i = 0; i < n; i++) {
cout << in_[i] << " ";
}
cout << endl;
}
return 0;
}
重点来了:
为什么二叉搜索树先序遍历字典序最小:
1.二叉搜索树: 左<根<右
2.想要保证属的形状相同就必须先插根节点 因为先查根节点 然后插别的就和根节点无关了
3.为了保证字典序最小 插完根节点 应该先插左子树 再插右子树
综上 先序遍历解决问题