Write a program to Delete a Tree
- Difficulty Level : Easy
- Last Updated : 17 Jul, 2022
To delete a tree, we must traverse all the nodes of the tree and delete them one by one. So, which traversal we should use – inorder transversal, preorder transversal, or the postorder transversal? The answer is simple. We should use the postorder transversal because before deleting the parent node, we should delete its child nodes first.
We can delete the tree with other traversals also with extra space complexity but why should we go for the other traversals if we have the postorder one available which does the work without storing anything in the same time complexity.
For the following tree, nodes are deleted in the order – 4, 5, 2, 3, 1.
Note : In Java automatic garbage collection happens, so we can simply make root null to delete the tree “root = null”;
The above deleteTree() function deletes the tree but doesn’t change the root to NULL which may cause problems if the user of deleteTree() doesn’t change root to NULL and tries to access the values using the root pointer. We can modify the deleteTree() function to take reference to the root node so that this problem doesn’t occur. See the following code.
Deleting node: 4 Deleting node: 5 Deleting node: 2 Deleting node: 3 Deleting node: 1 Tree deleted
Time Complexity: O(n)
Space Complexity: If we don’t consider size of stack for function calls then O(1) otherwise O(n)