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] ]题意是给定一个二叉树,然后对它进行层次遍历,而且每一层的遍历的左右顺序都会改变,例如第一层是从左到右,那么第二层就是从右到左,以此类推。这一道题大部分都和102题的层次遍历一样的。但是要加一个标识来判断该从左到右还是从右到左,当然也是有递归版本和非递归版本。递归版本如下:
Code:(LeetCode运行3ms)
/**
* 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;
zigzagLevelOrder(root, 1, result, true);
return result;
}
void zigzagLevelOrder(TreeNode* root, int level, vector<vector<int>> &result, bool leftToRight) {
if (!root) {
return;
}
if (result.size() < level) {
result.push_back(vector<int>());
}
if (leftToRight) {
result[level - 1].push_back(root -> val);
} else {
result[level - 1].insert(result[level - 1].begin(), root -> val);
}
zigzagLevelOrder(root -> left, level + 1, result, !leftToRight);
zigzagLevelOrder(root -> right, level + 1, result, !leftToRight);
}
};
Code:(LeetCode运行3ms)
/**
* 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 *> current, next;
TreeNode *pointer;
bool leftToRight = true;
if (!root) {
return result;
} else {
current.push(root);
}
while (!current.empty()) {
vector<int> temp;
while (!current.empty()) {
pointer = current.front();
current.pop();
if (leftToRight) {
temp.push_back(pointer -> val);
} else {
temp.insert(temp.begin(), pointer -> val);
}
if (pointer -> left) {
next.push(pointer -> left);
}
if (pointer -> right) {
next.push(pointer -> right);
}
}
leftToRight = !leftToRight;
result.push_back(temp);
swap(current, next);
}
return result;
}
};