版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010284636/article/details/81215073
Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution{
private:
vector<vector<int>> vec;
void bfs(TreeNode*root , int depth){
if(!root)
return;
if(root)
{
if(vec.size() < depth + 1) {
vector<int> tmp;
tmp.push_back(root->val);
vec.push_back(tmp);
}
else{
if(depth % 2 == 0){
vec[depth].push_back(root->val);
}
else{
vec[depth].insert(vec[depth].begin(),root->val);
}
}
}
if(root->left){
bfs(root->left, depth + 1);
}
if(root->right){
bfs(root->right, depth+1);
}
}
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
bfs(root, 0);
return vec;
}
};