VOOZH about

URL: https://www.geeksforgeeks.org/dsa/write-a-c-program-to-delete-a-tree/

⇱ Write a program to Delete a Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Write a program to Delete a Tree

Last Updated : 13 Jul, 2023

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 traversal, preorder traversal, or the postorder traversal? The answer is simple. We should use the postorder traversal 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.
 

👁 Example Tree


 

Note : In Java automatic garbage collection happens, so we can simply make root null to delete the tree "root = null";

Implementation:

Time Complexity: O(n) 
Space Complexity: If we don't consider size of stack for function calls then O(1) otherwise O(h)

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. 
Implementation:

Output:  

 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)

Comment
Article Tags: