103. Binary Tree Zigzag Level Order Traversal
/*
* @lc app=leetcode id=103 lang=cpp
*
* [103] Binary Tree Zigzag Level Order Traversal
*
* https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/description/
*
* algorithms
* Medium (60.32%)
* Likes: 11317
* Dislikes: 324
* Total Accepted: 1.4M
* Total Submissions: 2.3M
* Testcase Example: '[3,9,20,null,null,15,7]'
*
* Given the root of a binary tree, return the zigzag level order traversal of
* its nodes' values. (i.e., from left to right, then right to left for the
* next level and alternate between).
*
*
* Example 1:
*
*
* Input: root = [3,9,20,null,null,15,7]
* Output: [[3],[20,9],[15,7]]
*
*
* Example 2:
*
*
* Input: root = [1]
* Output: [[1]]
*
*
* Example 3:
*
*
* Input: root = []
* Output: []
*
*
*
* Constraints:
*
*
* The number of nodes in the tree is in the range [0, 2000].
* -100 <= Node.val <= 100
*
*
*/
// @lc code=start
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> res;
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
if(!root) return res;
levelOrder(root, 0);
return res;
}
void levelOrder(TreeNode* root, int level) {
if(!root) return;
if(res.size() == level)
res.push_back({});
if(level % 2 == 0) {
res[level].push_back(root->val);
} else {
res[level].insert(res[level].begin(), root->val);
}
levelOrder(root->left, 1 + level);
levelOrder(root->right, 1 + level);
}
};
// @lc code=end
- T:
- S:
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root)
{
vector<vector<int>> res;
queue<TreeNode*> q{{root}};
bool leftToRight = true;
while (!q.empty()) {
vector<int> nodesWithinLevel;
int qSize = q.size();
for (int i = 0; i < qSize; i++) {
TreeNode* node = q.front(); q.pop();
if (!node) continue;
if (leftToRight) {
nodesWithinLevel.push_back(node->val);
} else {
nodesWithinLevel.insert(nodesWithinLevel.begin(), node->val);
}
q.push(node->left);
q.push(node->right);
}
if (!nodesWithinLevel.empty()) {
res.push_back(nodesWithinLevel);
leftToRight = !leftToRight;
}
}
return res;
}
};
- T:
- S: