java: add «988. Smallest String Starting From Leaf»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-04-18 00:50:41 +02:00
parent d5634c4d42
commit e53159dd8d
Signed by: mfocko
GPG key ID: 7C47D46246790496

View 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));
}
}