LeetCode Binary Tree Zigzag Level Order Traversal
來源:程序員人生 發布時間:2015-05-14 09:37:38 閱讀次數:2528次
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.
OJ's Binary Tree Serialization:
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}"
.
題意:層次遍歷1顆樹,奇數層的時候翻轉。
思路:還是利用隊列層次遍歷,多1個判斷是不是翻轉的標記就好了,還有就是java是援用傳遞的,所以每次都要重新聲明1個對象,不然ans里面都是指向同1塊內存。
/**
* 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;
}
}
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈