Given a binary tree, write an algorithm to delete it completely from memory. The deletion process should ensure that every node in the binary tree is properly deallocated, thereby freeing up all used resources.
This is one of the basic problem in trees. if you are new to trees then this problem will help you build your foundation.
Input: root = [1,2,3,4,5]
1/ \
23/ \
45Output: The binary tree is deleted.Explanation: All nodes (1, 2, 3, 4, 5) are deallocated, ensuring the binary tree no longer exists in memory.
The binary tree can be thought of as a recursive data structure where each node contains references to two child nodes. To delete the entire tree, we need to recursively delete each node starting from the root and moving down to its children.
The purpose of recursion here ensures that nodes at the lowest level (leaf nodes) are deallocated first, followed by their parent nodes, ensuring nodes are deleted properly.
Traverse recursively: Start at the root and recursively traverse each subtree (left and right children).
Delete nodes: Deallocate the nodes in post-order fashion (delete left child, right child, then the parent).
Base condition: If the node is None, return immediately because there is nothing to delete.
To delete a binary tree, all node objects must be set to null, allowing garbage collection to handle the cleanup. In C/C++, however, you need to manually deallocate the memory.
classSolution {
publicvoiddeleteTree(TreeNode root) {
// Base condition - if the root is null, returnif (root ==null) {
return;
}
// Recursively delete the left subtree deleteTree(root.left);
// Recursively delete the right subtree deleteTree(root.right);
// Delete the current node System.out.println("Deleting node with value: "+ root.value);
root.left=null;
root.right=null;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
defdeleteTree(self, root):
# Base condition - if the root is None, returnif root isNone:
return# Recursively delete the left subtree self.deleteTree(root.left)
# Recursively delete the right subtree self.deleteTree(root.right)
# Delete the current node (in Python, making it None) print(f"Deleting node with value: {root.value}")
root.left =None root.right =None
⏰ Time complexity: O(n) - Every node in the tree needs to be visited once to delete it. For a binary tree with n nodes, we perform n deletions.
🧺 Space complexity: O(h) - The recursion stack will hold h function calls at most, where h is the height of the tree. In case of a completely balanced tree, h = log(n).