recursive function called trimTree, which removes (deletes) all the nodes at depth d or more in a BST.
QUESTION: Write a
recursive function called trimTree, which removes (deletes) all the
nodes at depth d or more in a BST. A Node* type pointer to the root of
the tree, and integer d are inputs to the function. Remember, the depth
of the root is 0. Also, make sure there are no memory leaks and all the new leaves
in the resultant tree have null children. Note: We do not know the size/total
depth of the tree in advance. (MARKS:
10)
SOLUTION
template <class type>
void
BinarySearchTree<type>::TrimTree(node *n, int d)
{
if
(!n)
return;
trimTree(n->left,d-1);
trimTree(n>right,d-1);
if
(d <= 0)
delete
n;
if
(d = = 1)
{
n->left
= NULL;
n->right
= NULL;
}
}
Comments
Post a Comment