<p>Given an integer <code>n</code>, return all the numbers in the range <code>[1, n]</code> sorted in lexicographical order.</p>

<p>You must write an algorithm that runs in&nbsp;<code>O(n)</code>&nbsp;time and uses <code>O(1)</code> extra space.&nbsp;</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 13
<strong>Output:</strong> [1,10,11,12,13,2,3,4,5,6,7,8,9]
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> n = 2
<strong>Output:</strong> [1,2]
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li>
</ul>


struct TrieNode {
    TrieNode * children[10];

    void addNumber(int n) {
        int pos = log10(n);
        addNumber(n, pos);
    }

    void addNumber(int n, int pos) {
        if (pos<0) {
            return ;
        }

        int currentPos = pos==0 ? n%10 : ((int)(n/pow(10, pos)))%10;
        if (this->children[currentPos] == nullptr) {
            this->children[currentPos] = new TrieNode();
        }

        this->children[currentPos]->addNumber(n, pos-1);
    }

    void addAllNumber(vector<int> & result, int vdeep=0) {
        for(int i=0;i<10;i++) {
            if (this->children[i]!=nullptr) {
                result.push_back(vdeep + i);
                this->children[i]->addAllNumber(result, (vdeep + i) * 10);
            }
        }
    }
};

class Solution {
public:
    vector<int> lexicalOrder(int n) {
        TrieNode root;
        for(int i=1;i<=n;i++) {
            root.addNumber(i);
        }

        vector<int> result;
        root.addAllNumber(result, 0);

        return result;
    }
};
21654