Preorder using stack


  • 0
    C

    Inspired by the DFS solution

    public List<Integer> lexicalOrder(int n) {
            Stack<Integer> stack = new Stack<>();
            List<Integer> result = new ArrayList<>();
            stack.push(0);
            
            while (!stack.isEmpty()) {
                int curr = stack.pop();
                if (curr != 0) {
                    result.add(curr);
                }
                for (int i = 9; i >= 0; i--) {
                    int child = 10 * curr + i;
                	if (child <= n && child != 0) {
                        stack.push(10 * curr + i);
                    }
                }
            }
            return result;
        }
    

Log in to reply
 

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