classSolution {publicList<Integer> lexicalOrder(int n) {List<Integer> res =newArrayList();int curNum =1;for (int i =1; i <= n; i++) {res.add(curNum);// Case 1: Traverse down to find lestmost nodeif (curNum *10<= n) { curNum *=10; }// Case 2: leftmost node found, do level traversalelseif (curNum %10!=9&& curNum +1<= n) {++curNum; }else {// Case 3.1: we are at the rightmost node,traverse up to upper levelwhile ((curNum /10) %10==9) { curNum /=10; } // Case 3.2: prepare to do traversal for the next tree curNum = curNum /10+1; } }return res; }}