32-II. 从上到下打印二叉树 II
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<vector<int>> levelOrder(TreeNode* root)
vector<vector<int>> levelOrder(TreeNode *i_root)
{
if(!i_root) return vector<vector<int>>{};
queue<TreeNode *> currentLayer{{i_root}};
queue<TreeNode *> nextLayer;
vector<vector<int>> prints;
vector<int> levelPrints;
while(!currentLayer.empty() || !nextLayer.empty())
{
if(currentLayer.empty())
{
prints.push_back(move(levelPrints));
swap(currentLayer, nextLayer);
}
else
{
auto node = currentLayer.front();
currentLayer.pop();
levelPrints.push_back(node->val);
if(node->left) nextLayer.push(node->left);
if(node->right) nextLayer.push(node->right);
}
}
prints.push_back(move(levelPrints));
return prints;
}
};