diff --git a/java/smallest-string-starting-from-leaf.java b/java/smallest-string-starting-from-leaf.java new file mode 100644 index 0000000..f140188 --- /dev/null +++ b/java/smallest-string-starting-from-leaf.java @@ -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)); + } +}