标签:
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] ]
confused what "{1,#,2,3}"
means? >
read more on how binary tree is serialized on OJ.
The serialization of a binary tree follows a level order traversal, where ‘#‘ signifies a path terminator where no node exists below.
Here‘s an example:
1 / 2 3 / 4 5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}"
.
题意:层次遍历一颗树,奇数层的时候翻转。
思路:还是利用队列层次遍历,多一个判断是否翻转的标记就行了,还有就是java是引用传递的,所以每次都要重新声明一个对象,不然ans里面都是指向同一块内存。
/** * Definition for binary tree * 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>> ans = new ArrayList<List<Integer>>(); if (root == null) return ans; Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); boolean reverse = false; while (!queue.isEmpty()) { List<Integer> tmp = new ArrayList<Integer>(); int num = queue.size(); for (int i = 0; i < num; i++) { TreeNode t = queue.poll(); tmp.add(t.val); if (t.left != null) queue.add(t.left); if (t.right != null) queue.add(t.right); } if (reverse) { Collections.reverse(tmp); reverse = false; } else reverse = true; ans.add(tmp); } return ans; } }
LeetCode Binary Tree Zigzag Level Order Traversal
标签:
原文地址:http://blog.csdn.net/u011345136/article/details/45396985