queue的方式
/**
* 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) return res;
vector<int> path;
queue<TreeNode*> q;
q.push(root);
q.push(nullptr);
int cnt = 0;
while(q.size())
{
auto tmp = q.front();
q.pop();
if(tmp)
{
path.push_back(tmp->val);
if(tmp->left) q.push(tmp->left);
if(tmp->right) q.push(tmp->right);
}
else
{
if(cnt % 2 != 0)
reverse(path.begin(), path.end());
res.push_back(path);
path.clear();
cnt++;
if(!q.size()) break;
q.push(nullptr);
}
}
return res;
}
};
DFS
/**
* 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 {
vector<vector<int>> res;
void dfs(TreeNode* root, int level)
{
if(!root) return;
if(res.size() < level + 1)
{
int cnt = level + 1 - res.size();
while(cnt--) res.push_back({});
}
res[level].push_back(root->val);
dfs(root->left, level + 1);
dfs(root->right, level + 1);
}
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
dfs(root, 0);
for(int i = 1; i < res.size(); i += 2)
reverse(res[i].begin(), res[i].end());
return res;
}
};
第二次写题
/**
* 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) return res;
vector<int> line;
queue<TreeNode*> q;
int level = 0;
q.push(root);
q.push(nullptr);
while(q.size())
{
TreeNode* tmp = q.front();
q.pop();
if(!tmp)
{
if(level) reverse(line.begin(), line.end());
res.push_back(line);
line.clear();
level ^= 1;
if(!q.size()) break;
q.push(nullptr);
}
else
{
if(tmp->left) q.push(tmp->left);
if(tmp->right) q.push(tmp->right);
line.push_back(tmp->val);
}
}
return res;
}
};