Share my java solution with two stacks


  • 0
    C
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        if (root != null) {
            Stack<TreeNode> stack1 = new Stack<>(), stack2 = new Stack<>();
            stack1.push(root);
            while (!stack1.isEmpty()) {
                if (!stack1.isEmpty()) {
                    List<Integer> arr = new ArrayList<>();
                    while (!stack1.isEmpty()) {
                        TreeNode node = stack1.pop();
                        arr.add(node.val);
                        if (node.left != null) {
                            stack2.push(node.left);
                        }
                        if (node.right != null) {
                            stack2.push(node.right);
                        }
                    }
                    list.add(arr);
                }
                if (!stack2.isEmpty()) {
                    List<Integer> arr = new ArrayList<>();
                    while (!stack2.isEmpty()) {
                        TreeNode node = stack2.pop();
                        arr.add(node.val);
                        if (node.right != null) {
                            stack1.push(node.right);
                        }
                        if (node.left != null) {
                            stack1.push(node.left);
                        }
                    }
                    list.add(arr);
                }
            }
        }
        return list;
    }

Log in to reply
 

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