Leetcode-103(Java) Binary Tree Zigzag Level Order Traversal
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,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
传送门:https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
/** * 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>> lists = new LinkedList<List<Integer>>(); if(root == null) return lists; Queue<TreeNode> currentLevel = new LinkedList<TreeNode>(); currentLevel.add(root); int cnt = 0; while(!currentLevel.isEmpty()) { int size = currentLevel.size(); List<Integer> list = new LinkedList<Integer>(); for(int i = 0; i < size; i ++) { TreeNode currentNode = new TreeNode(0); currentNode = currentLevel.poll(); list.add(currentNode.val); if(currentNode.left != null) currentLevel.add(currentNode.left); if(currentNode.right != null) currentLevel.add(currentNode.right); } if(cnt % 2 == 1) Collections.reverse(list); ++ cnt; lists.add(list); } return lists; } }