Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@thmain
Last active May 27, 2018 04:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thmain/49bc40e7c3e391f989b1 to your computer and use it in GitHub Desktop.
Save thmain/49bc40e7c3e391f989b1 to your computer and use it in GitHub Desktop.
public class DeleteTree {
// to delete a binary tree, we need to set all the node objects to null then
// garbage collection will take care of rest of the things
//do the post order traversal and set the node to null
public static Node deleteTree(Node root) {
if (root != null) {
deleteTree(root.left);
deleteTree(root.right);
System.out.println("Deleting Node:" + root.data);
root=null;
return root;
}
return null;
}
public static void main(String[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
deleteTree(root);
}
}
class Node {
int data;
Node left;
Node right;
public Node(int data) {
this.data = data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment