题解 | #二叉排序树#
二叉排序树
http://www.nowcoder.com/practice/b42cfd38923c4b72bde19b795e78bcb3
#include<iostream>
using namespace std;
typedef struct node {
int num;
struct node* left, * right;
node(int n) :num(n), left(NULL), right(NULL) {}
}TreeNode, * Tree;
void Insert(Tree& root, int num) {
if (root == NULL) {
root = (Tree)malloc(sizeof(TreeNode));
root->left = NULL;
root->right = NULL;
root->num = num;
}
else
if (num < root->num)
Insert(root->left, num);
else if(num > root->num)
Insert(root->right, num);
}
void Output1(Tree root) {
if (root == NULL)
return;
cout << root->num << " ";
Output1(root->left);
Output1(root->right);
}
void Output2(Tree root) {
if (root == NULL)
return;
Output2(root->left);
cout << root->num << " ";
Output2(root->right);
}
void Output3(Tree root) {
if (root == NULL)
return;
Output3(root->left);
Output3(root->right);
cout << root->num << " ";
}
int main()
{
int n, num, ans;
while (cin >> n) {
Tree root = NULL;
for (int i = 0; i < n; ++i) {
cin >> num;
Insert(root, num);
}
Output1(root);
cout << endl;
Output2(root);
cout << endl;
Output3(root);
cout << endl;
}
}