LeetCode/java/smallest-string-starting-from-leaf.java
2024-04-18 00:50:41 +02:00

33 lines
736 B
Java

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