• Post Reply Bookmark Topic Watch Topic
  • New Topic

Help for recursive method for a tree.  RSS feed

 
Werner Holt
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As one of the methods of my IntTree tree I have to implement a method that multiplies the level number with the sum of the nodes on the current level.
So far I have this, and it doesn't work. What I am wondering is am I on the right track at all with the second return statement? If yes, then do you have any suggestions how can I improve the way I count the levels, which obviously doesn't work. Thank you.

 
Stephan van Hulst
Saloon Keeper
Posts: 7992
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It depends on what you mean by "sum of the nodes on the current level". Do you need to sum the values of each sibling (in which case you need a breadth-first-traversal) or the recursive sum?
 
Werner Holt
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stephan van Hulst wrote:It depends on what you mean by "sum of the nodes on the current level". Do you need to sum the values of each sibling (in which case you need a breadth-first-traversal) or the recursive sum?

yes, so if i have this tree http://www.jade-cheng.com/uh/ta/ics-211-spring-2010/faq/bst.png i want 1*20 + 2*(10+30) +3*(5+15+25+40) and so on.
 
Stephan van Hulst
Saloon Keeper
Posts: 7992
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So, depthSum depends on the depth of the tree. Why don't you pass it as an argument to the recursive function?
 
Stephan van Hulst
Saloon Keeper
Posts: 7992
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And I'm assuming depthSum() is a method of your tree, then you don't need to pass the tree as an argument. This also saves you a null check.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!