java: add «988. Smallest String Starting From Leaf»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
d5634c4d42
commit
e53159dd8d
1 changed files with 33 additions and 0 deletions
33
java/smallest-string-starting-from-leaf.java
Normal file
33
java/smallest-string-starting-from-leaf.java
Normal file
|
@ -0,0 +1,33 @@
|
||||||
|
class Solution {
|
||||||
|
private String smallestFromLeaf(TreeNode node, StringBuilder sb) {
|
||||||
|
if (node == null) {
|
||||||
|
sb.reverse();
|
||||||
|
String reversed = sb.toString();
|
||||||
|
sb.reverse();
|
||||||
|
|
||||||
|
return reversed;
|
||||||
|
}
|
||||||
|
|
||||||
|
sb.append((char) ('a' + node.val));
|
||||||
|
String left = smallestFromLeaf(node.left, sb);
|
||||||
|
String right = smallestFromLeaf(node.right, sb);
|
||||||
|
sb.deleteCharAt(sb.length() - 1);
|
||||||
|
|
||||||
|
if (node.left == null) {
|
||||||
|
return right;
|
||||||
|
} else if (node.right == null) {
|
||||||
|
return left;
|
||||||
|
}
|
||||||
|
|
||||||
|
int cmp = left.compareTo(right);
|
||||||
|
if (cmp < 0) {
|
||||||
|
return left;
|
||||||
|
}
|
||||||
|
|
||||||
|
return right;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String smallestFromLeaf(TreeNode root) {
|
||||||
|
return smallestFromLeaf(root, new StringBuilder(8500));
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue