Skip to content

Instantly share code, notes, and snippets.

@thmain
Last active May 27, 2018
Embed
What would you like to do?
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