简体   繁体   中英

deleting binary search tree

I am trying to delete the whole binary search tree ( every node in the tree), which one of these functions do you think will work better?

private:
    struct Node {
        string value;
        Node* left;
        Node* right;
    };
    Node* root;

public:
    BST() {
        root = NULL;
    }

    ~BST() {
        delete root->left;
        delete root->right;
    }

or:

...
    void destroyTree (Node*& tree) {
        while (tree != NULL) {
            tree = tree->left;
            delete tree;
        }
        while (tree != NULL) {
            tree = tree->right;
            delete tree;
        }
        delete tree;
    }

Neither the proposed destructor ~BST() nor the proposed function destroyTree() of the class BST will delete the BST instance and will be better than the other.

Explanation 1 - what the destructor ~BST() is doing ?

The proposed source is simple delete root->left; followed by delete root->right; and will delete only 2 nodes of the BinarySearchTree.

  1. The node root is not check with NULL and otherwise is never deleted,
  2. The node root->left is not check with NULL too,
  3. The node root->right is not check with NULL too,

Explanation 2 - what the function destroyTree() is doing ?

Two while-loops to try the exploration of the tree, one for the left branch and one for the right branch. The condition (tree != NULL) is present only to exit from the loop but doesn't check if the current node could be deleted.

  1. With the left loop, only ->left nodes of the root->left will be deleted until tree->left == NULL and CRASH when trying to delete tree; ,
  2. Even after adding a if (tree==NULL) break; to exit from the loop before calling the delete tree; a new CRASH in the right loop,
  3. And the last delete tree; is a non-sense because at this position, tree is always '== NULL`.

Bonus Solution - based to a modification of the function destroyTree() .

A recursive function will be the simplest way to delete all created and inserted nodes. But be aware with the size of the BinarySearchTree and especially the deepest branch.

void destroyTree(Node *cur_node) {
    if (cur_node!=NULL) {
        // explore and delete on left
        destroyTree(cur_node->left); // recursive-call
        // explore and delete on right
        destroyTree(cur_node->right); // recursive-call
        // delete each node
        delete cur_node;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM