-2

Let's say we have a basic binary tree, capable of being searched recursively:

class BinaryTree{

    private int Element;
    private BinaryTree LeftNode;
    private BinaryTree RightNode;

    //Class Constructors

    //Class Methods

}

I initially learned this design of binary tree and a general tree mainly because it was simple and easy to use. However, someone discussed that with this design, every time i would expand the tree, a.k.a add an instance of BinaryTree to LeftNode or RightNode, the instantiating of another BinaryTree would also require reserving memory space to store all non-static methods of the class BinaryTree. As the tree grows exponentially, the amount of space required would also increase largely.

Is there a more efficient way to implement a recursive tree design, while staying true to object-oriented paradigms?

BJ Myers
  • 6,617
  • 6
  • 34
  • 50
Ediac
  • 833
  • 7
  • 14
  • What? No part of that concern makes sense. The tree isn't growing "exponentially," and you don't need extra memory space to store _methods._ You have the correct, efficient implementation already. – Louis Wasserman Jun 06 '15 at 16:31
  • 2
    "would also require reserving memory space to store all non-static methods of the class BinaryTree" - nope. Methods don't take up space in instances. – davmac Jun 06 '15 at 16:31
  • See http://stackoverflow.com/questions/730321/what-is-the-memory-overhead-of-a-java-method – fabian Jun 06 '15 at 16:33
  • and also this http://stackoverflow.com/questions/52353/in-java-what-is-the-best-way-to-determine-the-size-of-an-object – saljuama Jun 06 '15 at 16:38
  • There is a small overhead for objects (see http://stackoverflow.com/questions/258120/what-is-the-memory-consumption-of-an-object-in-java), but it's *proportional* to the number of nodes. The memory required to store a *balanced binary tree* is exponential in it's *depth*, which also means it's proportional to the number of nodes. You could of course store the fields of tree nodes in a array and also store indices of children in 2 other arrays, but that causes more problems than it solves... – fabian Jun 06 '15 at 17:04
  • For balanced binary trees you could use a array to store elements like a heap, see http://en.wikipedia.org/wiki/Binary_heap#Heap_implementation – fabian Jun 06 '15 at 17:09
  • I see, thanks for clearing my errors – Ediac Jun 06 '15 at 18:08

1 Answers1

2

Your assumption:

the instantiating of another BinaryTree would also require reserving memory space to store all non-static methods of the class BinaryTree.

is incorrect.

Class instance methods do not take up space with each new instance of a class. The only memory space taken up by an instance is its data.

bhspencer
  • 13,086
  • 5
  • 35
  • 44