leetcode 103. 二叉树的锯齿形层序遍历
程序员文章站
2022-05-21 08:16:42
...
/**
* 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;
if(!root) return result;
bool odd = true;
queue<TreeNode *> q,tmpQueue;
vector<int> subResult;
TreeNode *tmpNode;
q.push(root);
while(!q.empty()) {
tmpNode = q.front();
q.pop();
subResult.push_back(tmpNode->val);
if(tmpNode->left) tmpQueue.push(tmpNode->left);
if(tmpNode->right) tmpQueue.push(tmpNode->right);
if(q.empty()) {
if(!odd) reverse(subResult.begin(),subResult.end());
result.push_back(subResult);
odd = !odd;
q.swap(tmpQueue);
subResult.clear();
}
}
return result;
}
};
上一篇: CentOS 7系统下安装nginx-1.13的教程
下一篇: 安装docker-compose