Paul Clapham wrote:I don't know why your code is not doing what you want. But you shouldn't want that anyway. You shouldn't have to store the level in the node. Instead, here's how you find the level of a node:
If the node is the root, then its level is one. Or zero, if that's how you count. If the node is not the root, then its level is one greater than the level of its parent.
Antonio Nobrega wrote:Hmm..Ok so should i create a method to do that and return the level instead of storing the level in the node?
Also, why shouldnt i store the level?
Paul Clapham wrote:
Antonio Nobrega wrote:Hmm..Ok so should i create a method to do that and return the level instead of storing the level in the node?
Also, why shouldnt i store the level?
That's what I would do. If you store the level in the node, then when you move the node to a different place in the tree, you have to recalculate the level. That's just error-prone. You already found out that trying to store the level in the node was error-prone, didn't you?
Campbell Ritchie wrote:Your comparar method which takes two nodes is dangerous. Since trees can contain null nodes, that may suffer an Exception.
Your getLevel method appears to change the structure of the tree, which also appears dangerous.
I would do it by recursion myself.
Paul Clapham wrote:# If the node is the root, then its level is one. Or zero, if that's how you count.
# If the node is not the root, then its level is one greater than the level of its parent.
I earlier wrote:I would do it by recursion myself.
Campbell Ritchie wrote:yes, there are some hints:
Paul Clapham wrote:# If the node is the root, then its level is one. Or zero, if that's how you count.
# If the node is not the root, then its level is one greater than the level of its parent.I earlier wrote:I would do it by recursion myself.
And I now see your method uses local variables, so it doesn't actually change the tree. But the use of shadowing local variables is dubious, and that method is unnecessarily complicated.