LeetCode二叉树的层序遍历的输出

题目链接

 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) {
TreeNode* prev = root;
vector<vector<int>> vecvec;
if (!root)
return vecvec;
queue<TreeNode*> queue;
queue.push(root);
int levelcount = 1;
bool reve = false;
while (!queue.empty())
{
std::vector<int> vec;
int count = levelcount;
levelcount = 0;
while (count–)
{
prev = queue.front();
queue.pop();
vec.push_back(prev->val);
if (prev->left)
{
queue.push(prev->left);
                    levelcount++;
}
if (prev->right)
{
queue.push(prev->right);
                    levelcount++;
}
}
if (reve)
reverse(vec.begin(), vec.end());
vecvec.push_back(vec);
reve = !reve;
}
return vecvec;
}
};

点赞