<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>

class Solution {
public:
struct Node{
    Node* children[10];
    bool end=false;
    Node(){
    for(int i=0;i<10;i++) children[i]=NULL;
    }
};

struct Trie{
public:
    Node* root;
    Trie() {
        root=new Node();
    }
    void insert(string& str){
        Node* curr=root;
        for(auto c:str){
            if(curr->children[c-'0']==NULL){
                Node* node=new Node();
                curr->children[c-'0']=node;
            }
            curr=curr->children[c-'0'];
        }
        curr->end=true;
    }
};

void dfs(Node* root,int curr,vector<int>&ans){
    if(root==NULL) return;
    if(root->end==true) ans.push_back(curr);
    for(int i=0;i<=9;i++){
        if(root->children[i]) dfs(root->children[i],(curr*10)+(i),ans);
    }
}
    vector<int> lexicalOrder(int n) {
        Trie trie;
        for(int i=1;i<=n;i++){
            string s=to_string(i);
            trie.insert(s);
        }
        vector<int>ans;
        dfs(trie.root,0,ans);
        return ans;
    }
};

//Basic Recursion Solution 
//Tc=O(N) and SC=O(N)+log(n)for ASS

// class Solution {
// public:
//     void dfs(int i,int n,vector<int>&result){
//         if(i>n) return;
//         result.push_back(i);
//         for(int j=0;j<=9;j++) {
//             if(node*10+j>n) break;
//             dfs(node*10+j,n,result);
//         }
//     }
//     vector<int> lexicalOrder(int n) {
//         vector<int>result;
//         for(int i=1;i<=9;i++){
//             dfs(i,n,result);
//         }
//         return result;
//     }
// };
25346