用C++做leetcode的时候偶有出现函数返回类型需要从deque转到vector的情况,之前不熟悉相关语法,故做个记录备忘。
注意看倒数第56行代码的强制类型转换细节,用的是花括号!
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <iostream>
#include <deque>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode* root) {
vector<vector<int> > ans;
if (root == nullptr ) return ans;
deque<TreeNode*> deq;
int round = 0;
deq.push_back(root);
while (!deq.empty() ) {
deque<int> tempDeque;
int size = deq.size();
for (int i = 0; i < size; ++i) {
TreeNode* tempNode = deq.front();
deq.pop_front();
if (round % 2 == 0)
tempDeque.push_back(tempNode->val);
else
tempDeque.push_front(tempNode->val); //关键代码!!
if (tempNode->left != nullptr) deq.push_back(tempNode->left);
if (tempNode->right != nullptr) deq.push_back(tempNode->right);
}
++round;
//强制类型转换
ans.push_back(vector<int>{tempDeque.begin(), tempDeque.end() } );
}
return ans;
}
};
网友评论