• Post Reply Bookmark Topic Watch Topic
  • New Topic

tree implemention with sum function in java  RSS feed

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to use abstract generic class to implement tree nodes which have a sum function to sum each node and all its children values. Please check if my following thoughts are OK.
 
Bartender
Posts: 3271
82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch.

The code won't compile because you don't have a sum method that takes a List of nodes.
Also I'm not convinced your generic declarations are correct, why does your abstract Tree class mention Integer. Surely anything that extends Number would be a valid. That way you can have IntegerTree, LongTree, DoubleTree etc etc.
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

By Integer, do you mean java.lang.Integer? If so, you can dispense with the generics, (except that the List will be a List<Integer>). You can only ever enter one class, viz ja‍va.‍lang.Integer, which is a final class. Write Integer throughout.
Why have you not given the Node class a constructor? Then you pass the datum to its constructor. I presume you have other methods which populate that data structure with Integers, otherwise you will always have a tiny tree.
I would also suggest you do not need an abstract class. You are not going to have subclasses with different functionality for the sum() method, so I think you can dispense with the subclass, too.

I suggest you simplify the sum() method by getting rid of the if‑else. Look here for better style.
I also think you are going to have to go back to pencil and paper for the sum() method. You appear to be passing a List recursively to a method which gives its parameter type as Node. That needs a lot of thought.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!