Last active
May 27, 2018 04:27
-
-
Save thmain/49bc40e7c3e391f989b1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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