剑指Offer32-I.从上到下打印二叉树
1.BFS 队列 层序遍历 1
- 算法流程
1.首先初始化队列和一个数组容器。
2.送入头指针,看是否为空(特殊情况判断)。
3.获取队列的头,打印到容器数组,首元素出队列,先输入左子树,再输入右子树
class Solution {
public:
vector<int> levelOrder(TreeNode* root) {
vector<int>ans;
queue<TreeNode*>q;
q.push(root);
if(q.front()==nullptr) return ans;//判断队列是否为空的方法
while(!q.empty()){
TreeNode* head=q.front();//head是为了获取队列的头节点
ans.push_back(head->val);//送入vector
q.pop();//首元素出队
if(head->left){
q.push(head->left);//先输入左子树
}
if(head->right){
q.push(head->right);//再输入右子树
}
}
return ans;
}
};
知识点
时间复杂度/空间复杂度分析/面试场景如何作答
BFS/层序遍历/队列
- 时间复杂度:O(n)
- 空间复杂度: 空间复杂度为O(1)