1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;
class node {
public:
int data;
node* left;
node* right;
};
node* newNode(int data)
{
node* temp = new node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
node* constructTreeUtil(vector<int> pre, int* preIndex, int low,
int high, int size)
{
if (*preIndex >= size || low > high)
return NULL;
node* root = newNode(pre[*preIndex]);
*preIndex = *preIndex + 1;
if (low == high)
return root;
int i;
for (i = low; i <= high; ++i)
if (pre[i] > root->data)
break;
root->left = constructTreeUtil(pre, preIndex, *preIndex,
i - 1, size);
root->right
= constructTreeUtil(pre, preIndex, i, high, size);
return root;
}
node* constructTree(vector<int> pre, int size)
{
int preIndex = 0;
return constructTreeUtil(pre, &preIndex, 0, size - 1,
size);
}
void printInorder(node* node)
{
if (node == NULL)
return;
printInorder(node->left);
vector<uint64_t> tree;
tree.clear();
auto it = std::find(tree.begin(), tree.end(), node->data);
if (it == tree.end())
{
cout << node->data << "\n";
tree.push_back(node->data);
}
printInorder(node->right);
}
int main()
{
int n;
cin>>n;
vector<int> A(n);
for(auto &a:A) cin>>a;
node* root = constructTree(A,n);
printInorder(root);
cout<<"\n";
return 0;
}
|