算法
奇数行从左到又,偶数行从右到左
在层序遍历二叉树的基础上,判断当前层的奇偶性,奇数行正序输出,偶数行逆序输出
时间复杂度
参考文献
C++ 代码
/**
* 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;
vector<int>level;
vector<int>temp;
queue<TreeNode*>q;
q.push(root);
q.push(nullptr);
int n = 0;
while(q.size()){
auto t = q.front();
q.pop();
if(!t){
n++;
if(level.empty())break;
if(n%2==0)reverse(level.begin(),level.end());
res.push_back(level);
level.clear();
q.push(nullptr);
continue;
}
level.push_back(t->val);
if(t->left)q.push(t->left);
if(t->right)q.push(t->right);
}
return res;
}
};