题目链接:103.二叉树的锯齿形层序遍历
思路:双栈。
代码:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<List<Integer>> zigzagLevelOrder(TreeNode root) { if(root == null) return new ArrayList<>(); Deque<TreeNode> cur = new ArrayDeque<>(); Deque<TreeNode> next = new ArrayDeque<>(); List<List<Integer>> res = new ArrayList<>(); List<Integer> list = new ArrayList<>(); cur.push(root); boolean reverse = false; while(!cur.isEmpty()){ TreeNode node = cur.pop(); list.add(node.val); if(reverse){ if(node.right != null) next.push(node.right); if(node.left != null) next.push(node.left); }else{ if(node.left != null) next.push(node.left); if(node.right != null) next.push(node.right); } if(cur.isEmpty()){ Deque<TreeNode> t = cur; cur = next; next = t; reverse = !reverse; res.add(list); list = new ArrayList<>(); } } return res; } }