Java bfs solution


  • 0
    M
    public class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> res = new ArrayList<>();
            if(root == null) return res;
            Queue<TreeNode> que = new LinkedList<>();
            que.add(root);
            boolean isReverse = false;
            while(!que.isEmpty()){
                final int size = que.size();
                LinkedList<Integer> list = new LinkedList<>();
                for(int i=0; i<size; i++){
                    TreeNode node = que.poll();
                    if(node.left!=null) que.offer(node.left);
                    if(node.right!=null) que.offer(node.right);
                    if(isReverse){
                        list.addFirst(node.val);
                    } else {
                        list.addLast(node.val);
                    }
                }
                res.add(list);
                isReverse = !isReverse;
            }
            return res;
        }
    }
    

Log in to reply
 

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