Hello. There is a tree structure:

struct Tree { int value; Tree* left; Tree* right; Tree(int v) { value = v; left = nullptr; right = nullptr; } Tree() { value = 0; left = nullptr; right = nullptr; } }; 

There is also a function to add a new node:

 bool AddNode(Tree* root, int data) { if(root) { if(data < root->value) { AddNode(root->left, data); } else if(data > root->value) { AddNode(root->right, data); } else { return false; } } else { root = new Tree(data); } return true; } 

But for some reason there is a memory leak in this line:

 root = new Tree(data); 

Memory release:

 void DeleteTree(Tree* root) { if(root) { DeleteTree(root->left); DeleteTree(root->right); delete root; } } 

Please tell me what's wrong.

  • and how to free up resources? - KoVadim

1 answer 1

You pass root by value! Accordingly, if the procedure tries to change it, these changes are not visible outside the procedure, and the newly highlighted value is lost. Your tree will be empty, the elements will not actually be added.

Write like this:

 bool AddNode(Tree** ppRoot, int data) { if(*ppRoot) { Tree* pRoot = *ppRoot; if(data < pRoot->value) { AddNode(&(pRoot->left), data); } else if(data > pRoot->value) { AddNode(&(pRoot->right), data); } else { return false; } } else { *ppRoot = new Tree(data); } return true; } 
  • Agree you need to add a destructor to the structure - perfect
  • yes, here is the whole main: int _tmain (int argc, _TCHAR * argv []) {Tree * root = new Tree; int data; cout << "Enter a tree: \ n"; while (true) {cin >> data; if (cin.fail ()) {cout << "Data entry is completed \ n"; cin.clear (); break; } AddNode (root, data); } DeleteTree (root); return 0; } - rabbitinspace
  • those. instead of DeleteTree (root); need to use DeleteTree (& root); and in function to accept the pointer on the pointer? - rabbitinspace
  • Yeah, and in AddNode too. - VladD
  • one
    @devnikor: by the way, in DeleteTree it is just possible and by value. - VladD