#include<iostream>
using namespace std;
struct node
{
int num;
node* l;
node* r;
};
void built(node*& root, int num)
{
if (root == NULL)
{
root = (node*)malloc(sizeof(node));
if (root)
root->num = num;
return;
}
if (root->num == num)
return;
if (root->num > num)
built(root->l, num);
else
built(root->r, num);
}
void NLR(node* root)
{
if (root == NULL)
return;
cout << root->num << " ";
NLR(root->l);
NLR(root->r);
}
void LNR(node* root)
{
if (root == NULL)
return;
LNR(root->l);
cout << root->num << " ";
LNR(root->r);
}
void LRN(node* root)
{
if (root == NULL)
return;
LRN(root->l);
LRN(root->r);
cout << root->num << " ";
}
int main()
{
int length, a;
node* root;
while (cin >> length)
{
root = NULL;
for (size_t i = 0; i < length; i++)
{
cin >> a;
built(root, a);
}
NLR(root);
cout << endl;
LNR(root);
cout << endl;
LRN(root);
cout << endl;
}
}
不是第一次了,如果使用指针的话,vs2019很可能会出错。
上图是vs2019的结果。
http:/t.cn/AiKD0L5V这个链接是这道编程题。