-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathTries.java
More file actions
65 lines (55 loc) · 1.43 KB
/
Copy pathTries.java
File metadata and controls
65 lines (55 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package ds.tree;
/*
Tries:
Example
W
/ \
ISP A
\
N
/ \
T E
Input: WANE
Output: true
Input: WISP
Output: true
*/
// todo not done
public class Tries {
private TreeNode root;
private String res;
public void insert(String elem) {
if (elem == null) return;
if (root == null) root = new TreeNode(elem);
else insertHelper(root, elem);
}
private void insertHelper(TreeNode n, String elem) {
if (n == null) return;
if (n.elem.compareTo(elem) > 0) {
if (n.left != null) insertHelper(n.left, elem);
else n.left = new TreeNode(elem);
}
if (n.elem.compareTo(elem) < 0) {
if (n.right != null) insertHelper(n.right, elem);
else n.right = new TreeNode(elem);
}
}
public boolean find(String elem) {
if (elem == null) return false;
return findHelper(root, elem);
}
private boolean findHelper(TreeNode n, String elem) {
if (n == null) return false;
if (n.elem.equals(elem)) return true;
if (n.elem.compareTo(elem) > 0) return findHelper(n.left, elem);
return findHelper(n.right, elem);
}
private class TreeNode {
private String elem;
private TreeNode left;
private TreeNode right;
public TreeNode(String elem) {
this.elem = elem;
}
}
}