Simple JAVA solution using 2 stacks


  • 0
    S
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> arr = new ArrayList<List<Integer>>();
            Stack<TreeNode> lStack = new Stack<>();
            Stack<TreeNode> rStack = new Stack<>();
            if(root == null)
                return arr;
            lStack.push(root);
            while (!lStack.isEmpty() || !rStack.isEmpty()) {
                List<Integer> result = new ArrayList<Integer>();
                while(!lStack.isEmpty()) {
                    TreeNode node = lStack.pop();
                    result.add(node.val);
                    if(node.left != null)
                        rStack.push(node.left);
                    if(node.right != null)
                        rStack.push(node.right);
                }
                if(result.size() != 0)
                arr.add(new ArrayList(result));
                result = new ArrayList<>();
                while(!rStack.isEmpty()) {
                    TreeNode node = rStack.pop();
                    result.add(node.val);
                    if(node.right != null)
                        lStack.push(node.right);
                    if(node.left != null)
                        lStack.push(node.left);
                }
                if(result.size() != 0)
                arr.add(new ArrayList(result));
            }
            return arr;
        }
    }

Log in to reply
 

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