-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path988.java
More file actions
67 lines (66 loc) · 1.89 KB
/
988.java
File metadata and controls
67 lines (66 loc) · 1.89 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
66
67
__________________________________________________________________________________________________
sample 0 ms submission
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private String ans = "~"; // dummy value '~' > 'z'
public String smallestFromLeaf(TreeNode root) {
return dfs(root, "");
}
private String dfs(TreeNode n, String str) {
if (n == null) return ans;
str = (char)('a'+n.val) + str;
if (n.left == null && n.right == null && str.compareTo(ans) < 0){
ans = str;
}
dfs(n.left, str);
dfs(n.right, str);
return ans;
}
}
__________________________________________________________________________________________________
sample 37044 kb submission
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public String smallestFromLeaf(TreeNode root) {
// dfs
return dfs(root, "");
}
private String dfs(TreeNode root, String suffix) {
if (root == null) {
return suffix;
}
suffix = "" + (char)('a' + root.val) + suffix;
if (root.left == null && root.right == null) {
return suffix;
}
if (root.left == null) {
return dfs(root.right, suffix);
}
if (root.right == null) {
return dfs(root.left, suffix);
}
String left = dfs(root.left, suffix);
String right = dfs(root.right, suffix);
if(left.compareTo(right) <= 0) {
return left;
}
return right;
}
}
__________________________________________________________________________________________________