[GeeksForGeeks] Write a program to delete a tree
Write a program to delete a tree.
Solution.
To delete all tree nodes, we need to set all non-leaf nodes' children nodes to null. So for a given non-leaf node,
set its left child node to null, then set its right child node to null, then set the reference of this node to null.
This manifests a post order traversal of a given binary tree.
1 public class DeleteTree { 2 public void deleteTree(TreeNode node) { 3 if(node == null) { 4 return; 5 } 6 deleteTree(node.left); 7 deleteTree(node.right); 8 node = null; 9 } 10 }
Follow up question: Can you solve this problem without using recursion?