题目
思路
由于二叉搜索树的特性,不难发现,插入的时候,比节点小插左边,反之插右边即可
代码
#include<iostream>
using namespace std;
struct dot
{
int data;
dot* lc = NULL;
dot* rc = NULL;
void post_print()
{
if(!this) return;
if(this->lc)
this->lc->post_print();
if(this->rc)
this->rc->post_print();
cout << this->data << endl;
}
};
int main()
{
int* arr = new int[int(1e6)];
int num;
dot* root = new dot;
cin >> num;
root->data = num;
while(cin >> num)
{
dot* record = root;
dot* r_p = NULL;
int flag = 2;
while(record != NULL)
{
r_p = record;
if(num < r_p->data)
{
record = record->lc;
flag = 0;
}
else
{
record = record->rc;
flag = 1;
}
}
dot* temp = new dot;
temp->data = num;
if(flag == 0)
r_p->lc = temp;
else
r_p->rc = temp;
}
root->post_print();
}