Wrote a function to remove tree elements. It is necessary just elementwise, and not just the whole tree. It seems to be compiling for me, but immediately after launching the console, the program writes about the error and, accordingly, the console does not work as it did before writing the function. What could be the problem:
#include <iostream> #include <stdlib.h> using namespace std; struct Node { int x; Node *l,*r; }; void show(Node *&Tree) { if (Tree!=NULL) { show(Tree->l); show(Tree->r); } } void add_node(int x,Node *&MyTree) { if (MyTree) { if (x < MyTree->x) add_node(x, MyTree->l); else add_node(x, MyTree->r); } else { MyTree=new Node; MyTree->x=x; MyTree->l=MyTree->r=NULL; } } int cntx (Node *Tree, int deep) { if (!Tree || deep < 0) return 0; if (deep == 0) return 1; return cntx(Tree->l, --deep) + cntx(Tree->r, --deep); } void sumx (Node *Tree, int x[], int nx ) { for (int i = 0; i < nx; i++) cout << "level: " << x[i] << ' ' << cntx(Tree, x[i]) << " Nodes\n"; } Node* destroy(Node *Tree) { if( Tree->l == 0 ) { Node* right = Tree->r; *Tree = *right; right->l = 0; right->r = 0; delete right; } else { Node *c = Tree->l; Node *p = Tree->l; while( c->r ) { p = c; c = c->r; } p->r = c->l; c->l = NULL; Tree->x = c->x; delete c; } return Tree; } Node* remove(Node *Tree, int x) { if( Tree == NULL ) return 0; if( Tree->x < x ) { Tree->r = remove(Tree->r, x); return Tree; } else if( x < Tree->x ) { Tree->l = remove(Tree->l, x); return Tree; } return destroy(Tree); } void DeleteTree(Node *Tree) { if (Tree) { DeleteTree(Tree->l); DeleteTree(Tree->r); delete Tree; } } int main() { Node *Tree=NULL; int z,k; cout << "vvedit kilkist\n"; cin >> z; for (int i=0;i<z;i++) { cout << "vvedit chisla\n"; cin >> k; add_node(k,Tree); } show(Tree); cout << "All Tree levels cnt nodes\n"; int n; for (int i = 0; n = cntx(Tree, i); i++) cout << n << " nodes on level " << i << '\n'; DeleteTree(Tree); destroy(Tree); system("pause"); return 0; }