Tree java how to find a word
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.chi开发者_JS百科ldren);
} else {
return longestWord((DTN) d.children);
}
}
return newWord;
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 Node
s.
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;
}
精彩评论