32-I. 从上到下打印二叉树
1. 描述
从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
2. 例子
示例 1:
给定二叉树: [3,9,20,null,null,15,7],
[3,9,20,15,7]
3. 提示
- 节点总数 <= 1000
4. 题解
n 是 i_root 中的节点数目
时间复杂度: O(n)
空间复杂度: O(n)
class Solution
{
public:
// vector<int> levelOrder(TreeNode* root)
vector<int> levelOrder(TreeNode *i_root)
{
if(!i_root) return vector<int>{};
queue<TreeNode *> currentLayer{{i_root}};
queue<TreeNode *> nextLayer;
vector<int> prints;
while(!currentLayer.empty() || !nextLayer.empty())
{
if(currentLayer.empty())
{
swap(currentLayer, nextLayer);
}
else
{
auto node = currentLayer.front();
currentLayer.pop();
prints.push_back(node->val);
if(node->left) nextLayer.push(node->left);
if(node->right) nextLayer.push(node->right);
}
}
return prints;
}
};