class Solution {
public List<Integer> lexicalOrder(int n) {
List<Integer> res = new ArrayList();
for (int i = 1; i <= 9; i++) {
findLexicalOrder(i, n, res);
}
return res;
}
public void findLexicalOrder(int curNum, int n, List<Integer> res) {
if (curNum > n) {
return;
}
res.add(curNum);
for (int i = 0; i <= 9; i++) {
findLexicalOrder(curNum * 10 + i, n, res);
}
}
}
class Solution {
public List<Integer> lexicalOrder(int n) {
List<Integer> res = new ArrayList();
int curNum = 1;
for (int i = 1; i <= n; i++) {
res.add(curNum);
// Case 1: Traverse down to find lestmost node
if (curNum * 10 <= n) {
curNum *= 10;
}
// Case 2: leftmost node found, do level traversal
else if (curNum % 10 != 9 && curNum + 1 <= n) {
++curNum;
}
else {
// Case 3.1: we are at the rightmost node,traverse up to upper level
while ((curNum / 10) % 10 == 9) {
curNum /= 10;
}
// Case 3.2: prepare to do traversal for the next tree
curNum = curNum / 10 + 1;
}
}
return res;
}
}