Two-stack solution in Java


  • 0
    H

    The stack copy may waste a lot of time.

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            if(root == null){
                return res;
            }
            Stack<TreeNode> stack = new Stack<TreeNode>();
            Stack<TreeNode> stack2 = new Stack<TreeNode>();
            stack.push(root);
            int level = 1;
            while(!stack.isEmpty()){
                List<Integer> list = new ArrayList<Integer>();
                while(!stack.isEmpty()){
                    TreeNode node = stack.pop();
                    list.add(node.val);
                    if(level % 2 == 1){
                        if(node.left != null){
                            stack2.push(node.left);
                        }
                        if(node.right != null){
                            stack2.push(node.right);
                        }
                    }else{
                        if(node.right != null){
                            stack2.push(node.right);
                        }
                        if(node.left != null){
                            stack2.push(node.left);
                        }
                    }
                }
                level++;
                res.add(list);
                stack.addAll(stack2);
                stack2.clear();
            }
            return res;
        }

Log in to reply
 

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