层次优先遍历 BFS
先进行层次遍历,然后区分奇数偶数层(偶数层倒序输出)
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> result;
queue<TreeNode*> tmpQ;
int isRev = 0;
if(root == nullptr)
return result;
tmpQ.push(root);
while(tmpQ.size()!=0)
{
int len = tmpQ.size();
vector<int>levelResult;
for(int i=0;i<len;i++)
{
TreeNode* cur=tmpQ.front();
tmpQ.pop();
levelResult.push_back(cur->val);
if(cur->left!=nullptr) tmpQ.push(cur->left);
if(cur->right!=nullptr) tmpQ.push(cur->right);
}
if(isRev == 0)
{
result.push_back(levelResult);
isRev = 1;
}
else
{
reverse(levelResult.begin(),levelResult.end());//反转当前层序列
result.push_back(levelResult);
isRev = 0;
}
}
return result;
}
};