给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回锯齿形层次遍历如下:
[
[3],
[20,9],
[15,7]
]
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var zigzagLevelOrder = function(root) {
if (!root) return [];
const items = [];
let isOdd = true;
let levelNodes = [];
const queue = [root, null];
while(queue.length > 0) {
const t = queue.shift();
if (t) {
levelNodes.push(t.val)
if (t.left) {
queue.push(t.left)
}
if (t.right) {
queue.push(t.right)
}
} else {
if (!isOdd) {
levelNodes = levelNodes.reverse();
}
items.push(levelNodes)
levelNodes = [];
isOdd = !isOdd;
if (queue.length > 0) {
queue.push(null);
}
}
}
return items
};
/**
* 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) {
auto ret = vector<vector<int>>();
if (root == nullptr) return ret;
auto queue = vector<const TreeNode*>{root};
auto isOdd = true;
while (!queue.empty()) {
auto sz = queue.size();
auto level = vector<int>();
for (auto i = 0; i < sz; ++i) {
auto n = queue.front();
queue.erase(queue.begin());
if (isOdd) level.push_back(n->val);
else level.insert(level.begin(), n->val);
if (n->left != nullptr) queue.push_back(n->left);
if (n->right != nullptr) queue.push_back(n->right);
}
isOdd = !isOdd;
ret.push_back(level);
}
return ret;
}
};
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
auto ret = vector<vector<int>>();
zigzagLevelOrder(root, 0, ret);
return ret;
}
private:
void zigzagLevelOrder(const TreeNode* root, int level, vector<vector<int>>& ret) {
if (root == nullptr || level < 0) return;
if (ret.size() <= level) {
ret.push_back(vector<int>());
}
if (level % 2 == 0) ret[level].push_back(root->val);
else ret[level].insert(ret[level].begin(), root->val);
zigzagLevelOrder(root->left, level + 1, ret);
zigzagLevelOrder(root->right, level + 1, ret);
}
};