views:

257

answers:

2

I am trying to read a node that will find the longest word in a tree.

My method is public static int word(Node d). So how would I have to find the length of that node? Would I just use the string that was made in the class? The class I would use initializes a boolean, String: theWord and children. Here is what I got:

int newWord = 0;
int word = d.theWord.length();
if (d.isWord) {
    if (word > newWord) {
        newWord = word;
        return longestWord((DTN) d.children);
    } else {
        return longestWord((DTN) d.children);
    }
}
return newWord;
A: 

That's not really enough information to go on, but I'll take a shot in the dark anyway

public static int longest(Node d) {
  if (d == null) return 0;
  else return Math.max(longest(d.left), longest(d.right)) + 1;
}
Grumdrig
what If I can't call the d.left and right? Like the class only has a string and a boolean value??
Sam
@Sam - then it isn't a tree.
James Black
what about a digital tree??
Sam
@Sam - the problem with this whole question is that you are not expressing yourself clearly. For example, the term "digital tree" means nothing to me, and probably 99% of the people reading this.
Stephen C
@Sam, you cannot have a tree data structure in which you don't have a way for a node to point to child nodes.
BobbyShaftoe
A: 

Okay, there's a little more information. I'm still not at all clear on what's going on here, but here's another stab at what I think is basically what you might want:

String longestWord(Node d) {
  String result = d.theWord;
  for (Node c : d.children) {
     String w = longestWord(c);
     if (result.length < w.length) result = w;
  }
  return result;
}

This assumes d.children is some collection of Nodes.

Grumdrig
This function is using both loops and recursion; for what you are doing you only need to use one of those two methods.
R Samuel Klatchko
That is a puzzling statement...
Grumdrig
@R - not true. He is working on the assumption that each node has a list or array of child nodes; i.e. it is an N-ary tree not a binary tree. In this case, you have to iterate over the children, and then recurse for each one ... like he is doing.
Stephen C
Sorry, I'm not clear, but the method is an int. Also, I don't know if calling theWord, which is a public string would give me the string that I inputted. Also, the children is a Map that gets the character String. And, the parameter checked if it is null or not already.
Sam