这道题我给出两种解法:
第一种,是使用分层保存二叉树,然后奇数层不翻转,偶数层翻转
/**
* 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 == NULL)
return res;
res = levelOrder(root);
for(int i = 0; i < res.size(); ++i)
{
if(i & 0x1 != 0)
{
reverse(res[i].begin(), res[i].end());
}
}
return res;
}
vector<vector<int> > levelOrder(TreeNode* root)
{
int nextlevel = 0;
int tobeprinted = 1;
vector<int> curlevel;
vector<vector<int> > res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty())
{
curlevel.push_back(q.front() -> val);
if(q.front() -> left != NULL)
{
q.push(q.front() -> left);
nextlevel++;
}
if(q.front() -> right != NULL)
{
q.push(q.front() -> right);
nextlevel++;
}
q.pop();
tobeprinted--;
if(tobeprinted == 0)
{
res.push_back(curlevel);
curlevel.clear();
tobeprinted = nextlevel;
nextlevel = 0;
}
}
return res;
}
};
还有一种是剑指offer上利用两个栈的解法
class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode* root) {
stack<TreeNode*> s1;
stack<TreeNode*> s2;
vector<int> curlevel;
vector<vector<int> > res;
int tobeprinted = 1; //tobeprinted 和 nextlevel 用于标记换行
int nextlevel = 0;
int levelnum = 1; //用于指示当前的行号,从1开始
if(root == NULL)
return res;
s1.push(root);
while(!s1.empty() || !s2.empty())
{
if((levelnum & 0x1) == 1)
{
if(!s1.empty())
{
if(s1.top() != NULL)
{
curlevel.push_back(s1.top() -> val);
if(s1.top() -> left != NULL)
{
s2.push(s1.top() -> left);
nextlevel++;
}
if(s1.top() -> right != NULL)
{
s2.push(s1.top() -> right);
nextlevel++;
}
s1.pop();
}
}
}
else
{
if(!s2.empty())
{
if(s2.top() != NULL)
{
curlevel.push_back(s2.top() -> val);
if(s2.top() -> right != NULL)
{
s1.push(s2.top() -> right);
nextlevel++;
}
if(s2.top() -> left != NULL)
{
s1.push(s2.top() -> left);
nextlevel++;
}
s2.pop();
}
}
}
tobeprinted--;
if(tobeprinted == 0)
{
res.push_back(curlevel);
curlevel.clear();
tobeprinted = nextlevel;
nextlevel = 0;
levelnum++;
}
}
return res;
}
};