How to Remove Binary Tree in Java

Programmers use Java to develop a host of Web and desktop applications because of its cross-platform portability and its foundation built on object-oriented programming concepts. Java allows programmers to build and manipulate complex data structures on almost any system. A programmer could, for example, create and use a binary tree structure to store user data during the execution of the program. However, the programer might want to delete the binary tree, in which case she could delete each node, one by one.

Things You'll Need

  • Java Developer's Kit
  • Text editor or Java Development Environment
Show More

Instructions

    • 1

      Develop the deletion algorithm in a binary tree class. If a programmer develops a binary tree, she can create a deletion algorithm to clear out all data on all the nodes present. The outline for a binary tree class that includes a deletion function will look similar to this example:

      class BinaryTree{

      private Node left;
      private Node right;

      public void add(){
      //add item
      }

      public Node search(int item){
      //look for item
      }

      public Node getRoot(){
      //return root node
      }

      public void clearList(Node x){
      //deletes tree
      }
      }

    • 2

      Develop the deletion algorithm. If "clearList()" represents the function that will delete a binary tree, then the function has to go to each node and declare it as a "null" reference, which means Java garbage collection can delete it. The following example shows how to accomplish this using a post-order traversal, which recursively visits each node, and deletes both sub-trees of that node before deleting the node:

      public void clearList(Node x){

      if(x == null){
      return;
      }

      clearList(x.left);
      clearList(x.right);
      x = null;

      return;
      }

    • 3

      Call the deletion function. To empty an entire binary tree, the programmer could call the function using the root node of the tree. Also, the programmer could delete specific sub trees from the tree by getting a specific node in the tree. Assuming "BT" represents a binary tree, the following example shows how to accomplish this:

      BT.clearList(BT.search(5)); //deletes a sub tree under the node representing "5"
      BT.clearList(BT.getRoot()); //delete entire tree

Related Searches:

References

Comments

Related Ads

Featured