【剑指offer】【树】32-I.从上到下打印二叉树
题目链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/
迭代法(BFS)
使用队列,先将根入队,当队列不空时进行如下操作:
- 获取队首元素,队首元素出栈
- 将其插入res数组中
- 如果左孩子或右孩子不为空,分别将其入队
时间复杂度:O(N) : N 为二叉树的节点数量,即 BFS 需循环 NN 次
空间复杂度:O(N): 最差情况下,即当树为平衡二叉树时,最多有 N/2N/2 个树节点同时在 queue 中,使用 O(N)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<int> levelOrder(TreeNode* root) {
if(!root) return {};
vector<int> res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty())
{
auto tmp = q.front();
q.pop();
res.push_back(tmp -> val);
if(tmp -> left) q.push(tmp -> left);
if(tmp -> right) q.push(tmp -> right);
}
return res;
}
};
知识的价值不在于占有,而在于使用