add: 230219
This commit is contained in:
parent
b8916e9ab7
commit
692c3ba537
|
|
@ -0,0 +1,45 @@
|
|||
#include <vector>
|
||||
#include <utility>
|
||||
#include <queue>
|
||||
#include <algorithm>
|
||||
|
||||
struct TreeNode {
|
||||
int val;
|
||||
TreeNode* left;
|
||||
TreeNode* right;
|
||||
|
||||
explicit TreeNode(int x, TreeNode* left = nullptr, TreeNode* right = nullptr) : val(x), left(left), right(right) {}
|
||||
};
|
||||
|
||||
/**
|
||||
* 103. Binary Tree Zigzag Level Order Traversal
|
||||
*
|
||||
* 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).
|
||||
*/
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
static std::vector<std::vector<int>> zigzagLevelOrder(const TreeNode* root) {
|
||||
if (!root)
|
||||
return {};
|
||||
std::vector<std::vector<int>> ret {{}};
|
||||
std::queue<std::pair<const TreeNode*, int>> q;
|
||||
q.emplace(root, 0);
|
||||
for (int n = 0; !q.empty(); ) {
|
||||
const auto [ptr, lv] = q.front();
|
||||
q.pop();
|
||||
if (lv > n) {
|
||||
ret.emplace_back();
|
||||
++n;
|
||||
}
|
||||
ret.back().push_back(ptr->val);
|
||||
if (ptr->left)
|
||||
q.emplace(ptr->left, 1 + lv);
|
||||
if (ptr->right)
|
||||
q.emplace(ptr->right, 1 + lv);
|
||||
}
|
||||
for (int i = 1; i < ret.size(); i += 2)
|
||||
std::reverse(ret[i].begin(), ret[i].end());
|
||||
return ret;
|
||||
}
|
||||
};
|
||||
|
|
@ -16,7 +16,7 @@ ENDIF()
|
|||
# Optimisation
|
||||
# SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Ofast -march=native -mtune=native -finline-functions -ffast-math -fomit-frame-pointer")
|
||||
|
||||
ADD_EXECUTABLE(leetcode-cpp main.cpp 2302/230218.cpp 2302/230218-CN.cpp 2302/230219-CN.cpp)
|
||||
ADD_EXECUTABLE(leetcode-cpp main.cpp 2302/230218.cpp 2302/230218-CN.cpp 2302/230219-CN.cpp 2302/230219.cpp)
|
||||
|
||||
# ADD_SUBDIRECTORY(2112)
|
||||
# ADD_SUBDIRECTORY(2201)
|
||||
|
|
|
|||
Loading…
Reference in New Issue