mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
34 lines
736 B
Java
34 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));
|
||
|
}
|
||
|
}
|