103. Binary Tree Zigzag Level Order Traversal
- Total Accepted: 75753
- Total Submissions: 243834
- Difficulty: Medium
- Contributors: Admin
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,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
解题思路:
本题与使用BFS进行层次遍历类似,只是注意到当为第偶数层时,要将该层的结点从右到左遍历,即将层次遍历的结果反转即可。
代码展示:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> res;
if(!root) return res;
queue<TreeNode*> tra;
tra.push(root);
int precount=1;
int count =0;
bool rr = false;
while(tra.size())
{
vector<int> v;
while(precount--)
{
TreeNode * top = tra.front();
tra.pop();
if(top->left)
{
tra.push(top->left);
count++;
}
if(top->right)
{
tra.push(top->right);
count++;
}
v.push_back(top->val);
}
if(v.size())
{
if(rr)
{
reverse(v.begin(),v.end());
}
res.push_back(v);
}
precount = count;
count=0;
rr=!rr;
}
return res;
}
};