Skip to content

Commit e4f9c37

Browse files
committed
Add Tree Depth First Search/720_Longest_Word_in_Dictionary.java
1 parent 71afb1e commit e4f9c37

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
class Solution {
2+
private TrieNode root = new TrieNode();
3+
private String result = "";
4+
5+
public String longestWord(String[] words) {
6+
for (String word : words) {
7+
root.insert(word);
8+
}
9+
10+
dfs(root);
11+
return result;
12+
}
13+
14+
private void dfs(TrieNode root) {
15+
if (root == null) { return; }
16+
17+
if (root.word != null) {
18+
if (root.word.length() > result.length()) {
19+
result = root.word;
20+
}
21+
}
22+
23+
for (TrieNode child : root.children) {
24+
if (child != null && child.word != null) {
25+
dfs(child);
26+
}
27+
}
28+
}
29+
30+
private class TrieNode {
31+
private TrieNode[] children;
32+
private String word;
33+
34+
public TrieNode() {
35+
children = new TrieNode[26];
36+
word = null;
37+
}
38+
39+
public void insert(String word) {
40+
TrieNode runner = root;
41+
42+
for (char c : word.toCharArray()) {
43+
if (runner.children[c - 'a'] == null) {
44+
runner.children[c - 'a'] = new TrieNode();
45+
}
46+
47+
runner = runner.children[c - 'a'];
48+
}
49+
50+
runner.word = word;
51+
}
52+
}
53+
}

0 commit comments

Comments
 (0)