- 之字形打印二叉树
算法
(BFS) O(n)
宽度优先遍历,一层一层来做。即:
- 将根节点插入队列中;
- 创建一个新队列,用来按顺序保存下一层的所有子节点;
- 对于当前队列中的所有节点,按顺序依次将儿子插入新队列;
- 按从左到右、从右到左的顺序交替保存队列中节点的值;利用flag判断是否需要翻转
- 重复步骤2-4,直到队列为空为止。
时间复杂度
树中每个节点仅会进队出队一次,所以时间复杂度是 O(n)
代码实现:
/**
* 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 flag = true;//用于判断是否需要翻转
while(!q.empty()){
int size = q.size();
vector<int> tmp;
while(-- size >= 0){
auto t = q.front();
tmp.push_back(t->val);
q.pop();
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
if(!flag) reverse(tmp.begin(),tmp.end());
res.push_back(tmp);
}
return res;
}
};