虽说103 7ms 107 4ms但好歹是通过了,目前不是很追求最低运行时间,通过就好,8.22的102算法是个万金油啊
103 Binary Tree Zigzag Level Order Traversal
/**
* 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>> zigzagLevelOrder(TreeNode* root) {
//z字形遍历树
//层序遍历 + 单层次正向 + 双层次逆向
if(!root) return{};
//建立队列并将根入队
queue<TreeNode*> Node;
Node.push(root);
//建立结果二维数组
vector<vector<int>> res;
//开始遍历,增加一个count区分单双层
int count = 0;
while(!Node.empty()){
//每层都初始化,一次循环一层
vector<int> curr = {};
//确保只遍历该层结点
int n = Node.size();
for(int i = 0 ; i < n ; i++){
TreeNode* p = Node.front();
curr.push_back(p->val);
Node.pop();
//按顺序入队下一层的结点
if(p->left) Node.push(p->left);
if(p->right) Node.push(p->right);
}
if(count%2){
reverse(curr.begin() , curr.end());
}
count++;
res.push_back(curr);
}
return res;
}
};
107 Binary Tree Level Order Traversal II
/**
* 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>> levelOrderBottom(TreeNode* root) {
//层序遍历 倒着来 从最后一层往上走
//nodes的数量最多2000也不多,直接正着来然后reverse不就好了吗?
if(!root) return {};
queue<TreeNode*> NodeQueue;
NodeQueue.push(root);
vector<vector<int>> res;
while(!NodeQueue.empty()){
vector<int> curr = {};
int n = NodeQueue.size();
for(int i = 0 ; i < n ; i++){
TreeNode* p = NodeQueue.front();
curr.push_back(p->val);
NodeQueue.pop();
if(p->left){NodeQueue.push(p->left);}
if(p->right){NodeQueue.push(p->right);}
}
res.push_back(curr);
}
reverse(res.begin(),res.end());
return res;
}
};