Delete binary tree - design guidelines

I wrote code to remove all elements of the tree. We need suggestions for the following purposes:

  • In the reverseTreeStack method, is it possible to create a project without using the stack method method?
  • Can I create all the code in 1 method with a better design?

UPDATE: Changed return type reverseTreeStack for void.Removed additional variable for the stack.

public class DeleteTree { public static void deleteTree(BinaryTreeNode root) { Stack stack = new Stack(); reverseTreeStack(stack, root); while (!stack.isEmpty()) { BinaryTreeNode node = (BinaryTreeNode)stack.pop(); System.out.println("---------Deleting----------->" + node.getData()); node = null; } } public static void reverseTreeStack(Stack stack,BinaryTreeNode root) { if (root != null) { stack.push(root); reverseTreeStack(stack,root.getLeft()); reverseTreeStack(stack, root.getRight()); } } } 
+4
source share
4 answers

1) I think you can kill the return value and make it a void method, since you are directly manipulating the stack. So just

  Stack stack = new Stack(); reverseTreeStack(stack, root); // Now just use stack 

2) Do not condense things into one method. Destroying other methods will make your code easier to navigate and understand. The less each function responds, the more it will make sense to read it.

+1
source

Why do you need this? If I remember correctly, the JVM can free resources if there are no available references to the resource, so just setting the root of the node to null should free the whole tree.

+2
source

I think James is right, but if you want to practice tree traversal, or if you want to implement this in a language where you need to free memory manually, use recursion:

 void deleteTree(TreeNode node) { if(node==null)return; deleteTree(node.getLeft()); deleteTree(node.getRight()); System.out.printline("Deleting: "+node.getData()) node = null; } 

Also see Tracking after a schedule (this is the only one that works for deletion)

+2
source

Well, your reverseTreeStack method can give you a StackOverflowError if your tree is too large, so using a loop instead of recursion might be a better choice (unless you know that your trees will never be that big).

Also, why are you “deleting” each node? ( node = null actually just removes the link that you have in this method exactly ...) Usually just forgetting that root ( root = null ) will delete your tree if you structure it in the classic Node way (parent, leftChild, rightChild ) and do not store pointers to nodes anywhere else.

+1
source

All Articles