[LeetCode]Binary Tree Zigzag Level Order Traversal
题目链接: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; } };