Binary Tree Zigzag Level Order Traversal
Total Accepted: 3689 Total Submissions: 14306 My Submissions
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},
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
这个题是螺旋打印,其实和Binary Tree Level Order Traversal,Binary Tree Level Order Traversal II思路一样。
每次放在队列中的时候,判断一下,当前是哪一层。
假设层数为K,并且从1开始,那么在k % 2 == 1的时候,先放左子树,后放右子树,全部放入tempList以后,最后逆序放在队列中。
如果k % 2 == 0,先放右子树,后放左子树,全部放入tempList以后,最后逆序放在队列中。
这个过程如下:
假设我们有一棵这样的树。分析过程如下。
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) { ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(); if(root == null){ return list; } bfs(root,list); return list; } public void bfs(TreeNode root,ArrayList<ArrayList<Integer>> list){ Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); int k = 0; while (!queue.isEmpty()) { k++; int size = queue.size(); ArrayList<Integer> tempList = new ArrayList<Integer>(); ArrayList<TreeNode> nodeList = new ArrayList<TreeNode>(); if (k % 2 == 1) { for (int i = 0; i < size; i++) { TreeNode point = queue.peek(); queue.poll(); tempList.add(point.val); if (point.left != null) { nodeList.add(point.left); } if (point.right != null) { nodeList.add(point.right); } } } else { for (int i = 0; i < size; i++) { TreeNode point = queue.peek(); queue.poll(); tempList.add(point.val); if (point.right != null) { nodeList.add(point.right); } if (point.left != null) { nodeList.add(point.left); } } } int listSize = nodeList.size(); for (int i = listSize-1; i >= 0; i--) { queue.offer(nodeList.get(i)); } list.add(tempList); } } }