1
class Solution {
2
String result = null;
3

4
public String smallestFromLeaf(TreeNode root) {
5
build(root, new StringBuilder());
6
return result;
7
}
8

9
public void build(TreeNode root, StringBuilder str) {
10
if (root == null) return;
11

12
StringBuilder sb = new StringBuilder(str).insert(0, String.valueOf(intToChar(root.val)));
13

14
if (root.left == null && root.right == null) { // we are on a leaf node
15
result = result == null || sb.toString().compareTo(result) < 0 ? sb.toString() : result;
16
return;
17
}
18
build(root.left, sb); // build left child
19
build(root.right, sb); // build right child
20
}
21

22
// turns an int (0-25) into a Character ex: 0 -> a, 1 -> b, 2 -> c
23
public Character intToChar(int i) {
24
return (char) (i + 'a');
25
}
26
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0