題目鏈接: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] ]
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 \ 5The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}"
.題目描述:
題目要求對給定的二叉樹進行層序遍歷,並且對偶數層(設根結點所在的層爲1)的遍歷結果逆序輸出。
題目的根本在於對層的判斷,最方便的方法是使用雙隊列BFS。
所謂雙隊列BFS,是指用兩個隊列q1、q2,初始化時q1中只有根結點,q2爲空。接下來對q1進行出隊操作,但是把
q1的鄰接點壓入的是q2而非q1,這樣當q1爲空時一層的遍歷就結束了,接着再把q2的元素賦給q1,開始下一層。
這道題最大的坑在於空結點#並不是NULL,而是一個值爲0的結點,但是值爲0的結點也可能是一個非葉子結點,但是使用雙隊列法不會受到這個因素的干擾。
代碼如下:
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> outList;
if(root == NULL) return outList;
bool isReverse = false;
queue<TreeNode*> q1;
q1.push(root);
while(!q1.empty()){
queue<TreeNode*> q2;
vector<int> levelVec;
while(!q1.empty()){
TreeNode *t = q1.front();
q1.pop();
levelVec.push_back(t->val);
if(t->left) q2.push(t->left);
if(t->right) q2.push(t->right);
}
q1 = q2;
if(isReverse) reverse(levelVec.begin(),levelVec.end());
isReverse = !isReverse;
outList.push_back(levelVec);
}
return outList;
}
};