题目:
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]
]
分析:
这道题的要求是按照Z字形输出一棵二叉树。我的想法是使用BFS来求解这道题。
设两个变量cur和next来记录当前层次和下一层次还未遍历的结点数,设一个bool变量tag来标志当前层应该从左向右输出还是从右向左输出。
按BFS将每一个结点遍历一遍,当cur为0时表示当前层的结点已经全部遍历完,则将该层的结点按这一层应该存储的顺序存储到result中。
这道题的时间复杂度为O(N).
代码:
/**
* 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>> result;
queue<TreeNode*> q;
vector<int> vv;
if(root == NULL)
return result;
q.push(root);
int cur = 0,next = 0,depth = 0;
cur++;
bool tag = true; //true表示从左到右,false表示从右到左
while(!q.empty())
{
TreeNode* temp = q.front();
vv.push_back(temp->val);
cur--;
q.pop();
if(temp->left != NULL)
{
q.push(temp->left);
next++;
}
if(temp->right != NULL)
{
q.push(temp->right);
next++;
}
if(cur == 0) //当前层已经遍历完了
{
if(tag)
{
result.push_back(vector<int>());
for(int i = 0;i<vv.size();i++)
result[depth].push_back(vv[i]);
tag = false;
}
else
{
result.push_back(vector<int>());
for(int i = vv.size()-1;i>=0;i--)
result[depth].push_back(vv[i]);
tag = true;
}
cur = next;
next = 0;
depth++;
vv.clear();
}
}
return result;
}
};