Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7]
]
package leetCode; import java.util.ArrayList; import java.util.Deque; import java.util.LinkedList; import java.util.List; /** * Created by lxw, liwei4939@126.com on 2018/3/21. */ public class L103_BinaryTreeZigZagOrderTravel { public List<List<Integer>> zigzagLevelOrder(TreeNode root) { Deque<TreeNode> dq = new LinkedList<>(); List<List<Integer>> res = new ArrayList<>(); if (root == null){ return res; } boolean lr = true; TreeNode last = root; TreeNode nlast = null; dq.addFirst(root); List<Integer> lay = new ArrayList<>(); while (!dq.isEmpty()){ if (lr){ root = dq.pollFirst(); lay.add(root.val); if (root.left != null){ nlast = nlast == null? root.left : nlast; dq.offerLast(root.left); } if (root.right != null){ nlast = nlast == null ? root.right : nlast; dq.offerLast(root.right); } } else { root = dq.pollLast(); lay.add(root.val); if (root.right != null){ nlast = nlast == null ? root.right : nlast; dq.offerFirst(root.right); } if (root.left != null){ nlast = nlast == null ? root.left : nlast; dq.offerFirst(root.left); } } if (root == last){ lr = !lr; last = nlast; nlast = null; res.add(lay); lay = new ArrayList<>(); } } return res; } public static void main(String[] args){ L103_BinaryTreeZigZagOrderTravel tmp = new L103_BinaryTreeZigZagOrderTravel(); TreeNode root = new TreeNode(3); root.left = new TreeNode(9); root.right = new TreeNode(20); root.right.left = new TreeNode(15); root.right.right = new TreeNode(7); List<List<Integer>> res = tmp.zigzagLevelOrder(root); System.out.println(res); } }