Advertisement
AquaBlitz11

Mr. Duck's BST - Hard Construction Solution

Mar 18th, 2019
284
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.84 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int N = 1010;
  5. int pre[N];
  6.  
  7. struct node {
  8.     node *left;
  9.     node *right;
  10.     int data;
  11. };
  12.  
  13. node *solve(int l, int r) {
  14.     if (l > r)
  15.         return NULL;
  16.     node *root = new node;
  17.     root->data = pre[l];
  18.     for (int i = l+1; i <= r+1; ++i) {
  19.         if (pre[i] > pre[l] || i == r+1) {
  20.             root->left = solve(l+1, i-1);
  21.             root->right = solve(i, r);
  22.             break;
  23.         }
  24.     }
  25.     return root;
  26. }
  27.  
  28. void postorder(node *root) {
  29.     if (root == NULL)
  30.         return;
  31.     postorder(root->left);
  32.     postorder(root->right);
  33.     printf("%d ", root->data);
  34. }
  35.  
  36. int main()
  37. {
  38.     int n;
  39.     scanf("%d", &n);
  40.     for (int i = 0; i < n; ++i)
  41.         scanf("%d", &pre[i]);
  42.  
  43.     node *root = solve(0, n-1);
  44.     postorder(root);
  45.  
  46.     return 0;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement