DFS - but we know the arithmetic relationships of nodes


  • 0
    T
    public List<Integer> lexicalOrder(int n) 
    {
        ArrayList<Integer> list = new ArrayList<>();
        int x=1;
        while(true)
        {
            if(x<=n)
            {
                list.add(x);
                x*=10;  // first child
            }
            else
            {
                x=x/10+1;  // parent -> sibling
                while(x%10==0) x/=10;  // overflow
                if(x==1) return list;
            }
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.