题目描述
blablabla
样例
blablabla
算法1(BFS+辅助判断)
/**
* 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>> printFromTopToBottom(TreeNode* root) {
vector<vector<int> > res;
if (!root) return res;
queue<TreeNode*> q;
q.push(root);
bool isleft=false;
while (q.size()) {
int sz=q.size();
vector<int> tmp;
for (int i=0;i<sz;i++) {
auto cur=q.front();
q.pop();
tmp.push_back(cur->val);
if (cur->left) q.push(cur->left);
if (cur->right) q.push(cur->right);
}
isleft=!isleft;
if (!isleft) {
res.push_back(vector<int>(tmp.rbegin(),tmp.rend()));
}
else res.push_back(tmp);
}
return res;
}
};