Very straightforward solution in Java


  • 0
    W
    public class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if(root==null) return result;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
        for(int i=0;!stack.empty();i++){
            ArrayList<Integer> line = new ArrayList<Integer>();
            Stack<TreeNode> tempStack = new Stack<TreeNode>();
            while(!stack.empty()){
                root = stack.pop();
                line.add(root.val);
                TreeNode first = (((i&1)==0)?root.left:root.right);
                TreeNode second = (((i&1)==0)?root.right:root.left);
                if(first!=null) tempStack.push(first);
                if(second!=null) tempStack.push(second);
            }
            result.add(line);
            stack = tempStack;
        }
        return result;
    }
    

    }


Log in to reply
 

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