user3019324
user3019324

Reputation: 97

Recrusive Destructor for Binary Tree?

How would you implement a destructor for a binary tree recursively?

A node has an element, a pointer to a left node, and a pointer to a right node. Also, when would you set the left and right node pointers to NULL?

Upvotes: 1

Views: 860

Answers (3)

user207421
user207421

Reputation: 310885

How would you implement a destructor for a binary tree recursively?

Like so:

~BinaryTreeNode()
{
    delete _left;
    delete _right;
}

Also, when would you set the left and right node pointers to NULL?

Never in a destructor. You would do one or the other or maybe both in a node deletion method.

Upvotes: 1

James Reed
James Reed

Reputation: 491

Keeping o11c's answer in mind, if you choose not to use smart pointers and need to implement a destructor for nodes pointed to by bare pointers, use a post-order traversal.

http://en.wikipedia.org/wiki/Tree_traversal#Post-order

Upvotes: 1

o11c
o11c

Reputation: 16046

Destructors will recurse into members automatically. You shouldn't have to write a destructor manually hardly ever.

template<class T>
struct Node
{
    T data;
    std::unique_ptr<Node<T>> left, right;
};

template<class T>
struct BinaryTree
{
    std::unique_ptr<Node<T>> root;
};

Upvotes: 2

Related Questions