my accepted solution using 2 stack


  • 0
    S
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            if (root == null)
            {
                return res;
            }
            Stack<TreeNode> stck = new Stack<TreeNode>();
            Stack<TreeNode> altStck = new Stack<TreeNode>();
            stck.push(root);
            boolean rightSide=false;
            List<Integer> resLevel = new ArrayList<Integer>();
            while(!stck.isEmpty())
            {
                while(!stck.isEmpty())
                {
                    TreeNode node = stck.pop();
                    resLevel.add(node.val);
                    TreeNode next = rightSide?node.right:node.left;
                    if(next != null)
                    {
                        altStck.push(next);
                    }
                    next = rightSide?node.left:node.right;
                    if (next != null)
                    {
                        altStck.push(next);
                    }
                }
                if (!altStck.isEmpty())
                {
                    Stack temp = stck;
                    stck = altStck;
                    altStck = temp;
                    rightSide = !rightSide;
                }
                res.add(resLevel);
                resLevel = new ArrayList<Integer>();
            }
            return res;
        }
    }

Log in to reply
 

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