1

Well, i'm tried to build something like Binary Search Tree. And after some iterations i'm creating newnode and it has pointer which has already used. How to solve this problem, without classes. For example test, 9 1 7 5 21 22 27 25 20 10 Build it in reverse order (last is root, first cnt of vertex)

Here code:

#include <bits/stdc++.h>

using namespace std;

const int N = 3000;
int n;
int a[N];

struct node {
    int v;
    node *left, *right;
};
vector<int> ans;
node qwe;

void add(node *root, int elem) {
    if (elem > root->v) {
        if (root->right != NULL) {
            add(root->right, elem);
        } else {
            node newnode{};
            newnode.v = elem;
            newnode.right = NULL;
            newnode.left = NULL;
            node *lsls;
            lsls = &newnode;
            root->right = lsls;
        }
    } else {
        if (root->left != NULL) {
            add(root->left, elem);
        } else {
            node newnode;
            newnode.v = elem;
            newnode.right = NULL;
            newnode.left = NULL;
            node *lsls;
            lsls = &newnode;
            root->left = lsls;
        }
    }
}

int main() {

    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cin >> n;
    for (int i = 0; i < n; ++i) {
        cin >> a[i];
    }
    qwe.v = a[n - 1];
    qwe.left = NULL;
    qwe.right = NULL;
    node *pointer;
    pointer = &qwe;
    for (int i = n - 2; i > -1; --i) {
        add(pointer, a[i]);
    }
    pointer = &qwe;

    return 0;
}
J. Antonio Perez
  • 8,918
  • 16
  • 37
challenger
  • 11
  • 1
  • 4
    [Why should I not use `#include ?`](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – R Sahu Feb 25 '20 at 17:07
  • 2
    why without classes? You are already using a class. `struct` is one way to define a class: https://stackoverflow.com/a/54596/4117728 – 463035818_is_not_a_number Feb 25 '20 at 17:12
  • i wanna understand why this happens and find mistake – challenger Feb 25 '20 at 17:15
  • 3
    `node newnode` creates a local object named `newnode` of the class `node`. It is automatically allocated (usually on the stack). When you exit the `add` function, this object ceases to be valid, and any access to it is undefined behavior. You should not store its address for use outside of the `add` function. If you want memory to persist, use `new` to dynamically allocate memory. – JohnFilleau Feb 25 '20 at 17:17
  • *Build it in reverse order (last is root, first cnt of vertex)* Not sure why this is important. You seem to be building a binary tree, not a linked list. – R Sahu Feb 25 '20 at 17:23
  • Thank you, John! – challenger Feb 25 '20 at 17:43

0 Answers0