https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
掌握vector的头插法 v.insert(v.begin(),val)之后,这道题就变得很简单了。
1.递归
/**
* 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) {
dfs(root, 1);
return result;
}
vector<vector<int>> result;
void dfs(TreeNode* root, int depth){
if(root==nullptr)return;
if(result.size()< depth){
vector<int> tmp;
result.push_back(tmp);
}
//在层次遍历的基础上进行改动:当层号为奇数时,正常插入;
//当层号为偶数时,向头部插入即可
if(depth%2!=0)
result[depth-1].push_back(root->val);
else
result[depth-1].insert(result[depth-1].begin(), root->val);
if(root->left != nullptr)
dfs(root->left, depth+1);
if(root->right != nullptr)
dfs(root->right, depth+1);
}
};
2.非递归
/**
* 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;
queue<TreeNode*> a, b;
if(root!=nullptr)
a.push(root);
while(!a.empty() || !b.empty()){
TreeNode* tmp;
vector<int> normal;
while(!a.empty() ){//队列a中的值每次正常插入
tmp = a.front();
a.pop();
normal.push_back(tmp->val);
if(tmp->left!=nullptr)
b.push(tmp->left);
if(tmp->right!=nullptr)
b.push(tmp->right);
}
if(!normal.empty())
result.push_back(normal);
vector<int> reverse;
while(!b.empty()){//队列b中的值每次取出来,采用头插法
tmp = b.front();
b.pop();
reverse.insert(reverse.begin(), tmp->val);
if(tmp->left!=nullptr)
a.push(tmp->left);
if(tmp->right!=nullptr)
a.push(tmp->right);
}
if(!reverse.empty())
result.push_back(reverse);
}
return result;
}
};